@override
void initState() {
super.initState();
readCounter().then((int value) {
setState(() {
count = value;
});
});
}
Future getLocalFile() async {
String dir = (await getApplicationDocumentsDirectory()).path;
return new File(‘$dir/counter.txt’);
}
Future readCounter() async {
try {
File file = await getLocalFile();
String contents = await file.readAsString();
return int.parse(contents);
} on FileSystemException {
return 0;
}
}
Future incrementCounter() async {
setState(() {
count++;
});
await (await getLocalFile()).writeAsString(‘$count’);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: new AppBar(title: new Text(‘文件操作’)),
body: new Center(
child: new Text(‘点击了 $count 次’),
),
floatingActionButton: new FloatingActionButton(
onPressed: incrementCounter,
tooltip: ‘Increment’,
child: new Icon(Icons.add),
),
),
);
}
}
2.添加引用

path_provider: ^0.4.1

flutter ios 打开文件获取文件 flutter文件操作_flutter

3.解释源代码
import ‘dart:io’;
import ‘dart:async’;
import ‘package:flutter/material.dart’;
import ‘package:path_provider/path_provider.dart’;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
//记录点击次数
int count = 0;
@override
void initState() {
super.initState();
//从文件读取点击次数
readCounter().then((int value) {
setState(() {
count = value;
});
});
}
Future getLocalFile() async {
// 获取应用目录
String dir = (await getApplicationDocumentsDirectory()).path;
return new File(‘$dir/counter.txt’);
}
Future readCounter() async {
try {
File file = await getLocalFile();
// 读取点击次数(以字符串)
String contents = await file.readAsString();
return int.parse(contents);
} on FileSystemException {
return 0;
}
}