读写File

在initstat里面将文件里面存储的数值赋值给要显示的组件,这样可以在App打开时就恢复上次App存储的数据;
每次数值变化就随之存储到文件;
下面是一个完整的示例:
import 'package:flutter/material.dart';

import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';

void main()=>runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
int count=0;
File file;

Future<File> getAppLocation()async{
String path=(await getApplicationDocumentsDirectory()).path;
path='$path/count.txt';
File file=File(path);
return file;
}

Future writeCountToFile()async{
await (await getAppLocation()).writeAsString('$count');
}

Future<String> readCountFromFile()async{
String value = await (await getAppLocation()).readAsString();
return value;
}
@override
void initState() {
// TODO: implement initState
readCountFromFile().then((value){
setState(() {
count=int.parse(value);
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('勇往直前'),),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
setState(() {
count++;
});
writeCountToFile();
}),
body: Center(
child: ActionChip(
label: Text('点击了$count次'),
onPressed: (){
setState(() {
count++;
});
writeCountToFile();
},
),
),
);
}
}

猜你喜欢

转载自www.cnblogs.com/braveheart007/p/10835692.html