文件读写

获取文件地址并返回该文件(获取路径是anync await异步操作):
Future<File> _getLocalFile() async {
    String dir = (await getApplicationDocumentsDirectory()).path;   // get the path to the document directory.
return 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; } }//用int.parse(contents);把String转化为int.


向指定的文件路径写入文件,这是异步操作,注意两个await,都不落下;
Future<Null> _incrementCounter() async {
    setState(() {
      _counter++;
    });
    // write the variable as a string to the file
    await (await _getLocalFile()).writeAsString('$_counter');
  }


下面是一个示例:
直接拷贝到main.dart就可以使用,注意引入依赖:
path_provider


import 'dart:io';

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: FlutterDemo(),
),
);
}

class FlutterDemo extends StatefulWidget {
FlutterDemo({Key key}) : super(key: key);

@override
_FlutterDemoState createState() => _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 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 Scaffold(
appBar: AppBar(title: new Text('Flutter Demo')),
body: Center(
child: Text('Button tapped $_counter time${
_counter == 1 ? '' : 's'
}.'),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}


整个示例看下来可以发现,所有的异步操作要么在initstate里面,要么在onpress里面。所以咱们以后主要使用的异步操作就暂时先放在这两个地方!
posted @ 2019-06-17 20:52  braveheart007  阅读(374)  评论(0编辑  收藏  举报