Flutter 教程
- 第1节:Flutter Windows安装
- 第2节:Flutter MacOS安装
- 第3节:Flutter Linux安装
- 第4节:Flutter 配置编辑器
- 第5节:Flutter 编写第一个Flutter应用
- 第6节:Flutter Widget框架概述
- 第7节:Flutter Widget目录
- 第8节:Flutter 构建布局
- 第9节:Flutter 布局方法
- 第10节:Flutter 布局多个widgets
- 第11节:Flutter 常用布局widgets
- 第12节:Flutter 添加交互
- 第13节:Flutter 手势
- 第14节:Flutter 动画
- 第15节:Flutter 自定义字体
- 第16节:Flutter 盒约束
- 第17节:Flutter 资源和图片
- 第18节:Flutter 文本输入
- 第19节:Flutter 路由和导航
- 第20节:Flutter 国际化
- 第21节:Flutter 使用 packages
- 第22节:Flutter 开发 packages
- 第23节:Flutter 平台特定的代码
- 第24节:Flutter 文件读写
- 第25节:Flutter 网络和Http
- 第26节:Flutter JSON和序列化
- 第27节:Flutter 使用 Flutter IDE
- 第28节:Flutter 使用热重载
- 第29节:Flutter 测试应用
- 第30节:Flutter 调试应用
- 第31节:Flutter 检查用户界面
- 第32节:Flutter Android构建发布
- 第33节:Flutter iOS构建发布
- 第34节:Flutter 升级安装
- 第35节:Flutter 格式化代码
Flutter 文件读写
介绍
PathProvider 插件提供了一种平台透明的方式来访问设备文件系统上的常用位置。该类当前支持访问两个文件系统位置:
- 临时目录: 系统可随时清除的临时目录(缓存)。在iOS上,这对应于NSTemporaryDirectory() 返回的值。在Android上,这是getCacheDir()返回的值。
- 文档目录: 应用程序的目录,用于存储只有自己可以访问的文件。只有当应用程序被卸载时,系统才会清除该目录。在iOS上,这对应于NSDocumentDirectory。在Android上,这是AppData目录。
一旦你的Flutter应用程序有一个文件位置的引用,你可以使用dart:ioAPI来执行对文件系统的读/写操作。有关使用Dart处理文件和目录的更多信息,请参阅此概述 和这些示例。
读写文件的示例
以下示例展示了如何统计应用程序中按钮被点击的次数(关闭重启数据不丢失):
- 通过 flutter create 或在IntelliJ中 File > New Project 创建一个新Flutter App.
- 在pubspec.yaml文件中声明依赖 PathProvider 插件
- 用一下代码替换 lib/main.dart中的:
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),
),
);
}
}