PathProvider 插件提供了一種平臺(tái)透明的方式來(lái)訪問(wèn)設(shè)備文件系統(tǒng)上的常用位置。該類當(dāng)前支持訪問(wèn)兩個(gè)文件系統(tǒng)位置:
一旦你的Flutter應(yīng)用程序有一個(gè)文件位置的引用,你可以使用dart:ioAPI來(lái)執(zhí)行對(duì)文件系統(tǒng)的讀/寫操作。有關(guān)使用Dart處理文件和目錄的更多信息,請(qǐng)參閱此概述 和這些示例。
以下示例展示了如何統(tǒng)計(jì)應(yīng)用程序中按鈕被點(diǎn)擊的次數(shù)(關(guān)閉重啟數(shù)據(jù)不丟失):
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<FlutterDemo> {
int _counter;
@override
void initState() {
super.initState();
_readCounter().then((int value) {
setState(() {
_counter = value;
});
});
}
Future<File> _getLocalFile() async {
// get the path to the document directory.
String dir = (await getApplicationDocumentsDirectory()).path;
return new File('$dir/counter.txt');
}
Future<int> _readCounter() async {
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<Null> _incrementCounter() async {
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),
),
);
}
}
更多建議: