35 文件操作
1.源代码
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<MyApp> {
int count = 0;
@override
void initState() {
super.initState();
readCounter().then((int value) {
setState(() {
count = value;
});
});
}
Future<File> getLocalFile() async {
String dir = (await getApplicationDocumentsDirectory()).path;
return new File('$dir/counter.txt');
}
Future<int> readCounter() async {
try {
File file = await getLocalFile();
String contents = await file.readAsString();
return int.parse(contents);
} on FileSystemException {
return 0;
}
}
Future<Null> 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
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/58d2a5cc8351195c3ad6e22f90438aa0.png)
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<MyApp> {
int count = 0;
@override
void initState() {
super.initState();
readCounter().then((int value) {
setState(() {
count = value;
});
});
}
Future<File> getLocalFile() async {
String dir = (await getApplicationDocumentsDirectory()).path;
return new File('$dir/counter.txt');
}
Future<int> readCounter() async {
try {
File file = await getLocalFile();
String contents = await file.readAsString();
return int.parse(contents);
} on FileSystemException {
return 0;
}
}
Future<Null> 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),
),
),
);
}
}
4.效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/726c6118018025e6b39d3d78fa86b1bb.gif)