介紹
PathProvider 插件提供了(le)一種平台透明(míng)的方式來(lái)訪問設備文(wén)件系統上(shàng)的常用(yòng)位置。該類當前支持訪問兩個文(wén)件系統位置:
臨時(shí)目錄: 系統可随時(shí)清除的臨時(shí)目錄(緩存)。在iOS上(shàng),這(zhè)對(duì)應于NSTemporaryDirectory() 返回的值。在Android上(shàng),這(zhè)是getCacheDir()返回的值。
文(wén)檔目錄: 應用(yòng)程序的目錄,用(yòng)于存儲隻有自(zì)己可以訪問的文(wén)件。隻有當應用(yòng)程序被卸載時(shí),系統才會(huì)清除該目錄。在iOS上(shàng),這(zhè)對(duì)應于NSDocumentDirectory。在Android上(shàng),這(zhè)是AppData目錄。
一旦你(nǐ)的Flutter應用(yòng)程序有一個文(wén)件位置的引用(yòng),你(nǐ)可以使用(yòng)dart:ioAPI來(lái)執行對(duì)文(wén)件系統的讀/寫操作(zuò)。有關使用(yòng)Dart處理(lǐ)文(wén)件和(hé)目錄的更多信息,請(qǐng)參閱此概述 和(hé)這(zhè)些(xiē)示例。
讀寫文(wén)件的示例
以下(xià)示例展示了(le)如何統計(jì)應用(yòng)程序中按鈕被點擊的次數(關閉重啓數據不丢失):
通過 flutter create 或在IntelliJ中 File > New Project 創建一個新Flutter App.
在pubspec.yaml文(wén)件中聲明(míng)依賴 PathProvider 插件
用(yòng)一下(xià)代碼替換 lib/main.dart中的:
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(primarySwatch: Colors.blue),
home: new FlutterDemo(),
),
);
}
class FlutterDemo extends StatefulWidget {
FlutterDemo({Key key}) : super(key: key);
@override
_FlutterDemoState createState() => new _FlutterDemoState();
}
class _FlutterDemoState extends State
int _counter;
@override
void initState() {
super.initState();
_readCounter().then((int value) {
setState(() {
_counter = value;
});
});
}
Future
// get the path to the document directory.
String dir = (await getApplicationDocumentsDirectory()).path;
return new File('$dir/counter.txt');
}
Future
try {
File file = await _getLocalFile();
// read the variable as a string from the file.
String contents = await file.readAsString();
return int.parse(contents);
} on FileSystemException {
return 0;
}
}
Future
setState(() {
_counter++;
});
// write the variable as a string to the file
await (await _getLocalFile()).writeAsString('$_counter');
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('Flutter Demo')),
body: new Center(
child: new Text('Button tapped $_counter time${
_counter == 1 ? '' : 's'
}.'),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
網站(zhàn)建設開(kāi)發|APP設計(jì)開(kāi)發|小(xiǎo)程序建設開(kāi)發