getTemporaryDirectory:获取临时目录
getApplicationDocumentsDirectory:获取应用文档目录
getExternalStorageDirectory:获取外部存储目录,注意:IOS没有外部存储目录的概念,所以无法获取。
这里简单模拟日志记录效果:
1、在pubspec.yaml中添加插件:
path_provider: ^1.6.212、详细代码:
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 StatelessWidget { const MyApp({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: MaterialApp( title: 'path_provider文件存储示例', debugShowCheckedModeBanner: false, home: FirstPage(), ), ); } } class FirstPage extends StatefulWidget{ FirstPage({Key key}) : super(key:key); _FirstPageState createState() => _FirstPageState(); } class _FirstPageState extends State<FirstPage>{ int log_id = 0; String log_info = ''; File file; @override void initState() { super.initState(); readLogInfo().then((String value){ setState(() { log_info = value; }); }); } //获取路径,不存在,就创建 Future<File> getFile() async{ String dir = (await getApplicationDocumentsDirectory()).path; if(file == null){ file = File('$dir/log.txt'); } return file; } //读取文件内容 Future<String> readLogInfo() async{ try{ File file = await getFile(); String content = await file.readAsString(); return content; }on FileSystemException{ return ''; } } //写入文件 Future<Null> writeLogInfo() async{ setState(() { log_id++; }); await (await getFile()).writeAsString('日志信息:$log_id\n',mode: FileMode.append); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('path_provider文件存储示例'), ), body: Center( child: Text('$log_info'), ), floatingActionButton: FloatingActionButton( onPressed: writeLogInfo, tooltip: '写入日志', child: Icon(Icons.add), ), ); } }