文檔app
import 'dart:io'; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Ajnauw', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { String value; // 每次input的值 String allText = ''; // 從本地文件獲取的值 /** * 此方法返回本地文件地址 */ Future<File> _getLocalFile() async { // 獲取文檔目錄的路徑 Directory appDocDir = await getApplicationDocumentsDirectory(); String dir = appDocDir.path; final file = new File('$dir/demo.txt'); // print(file); return file; } /** * 保存value到本地文件裏面 */ void _saveValue() async { try { File f = await _getLocalFile(); IOSink slink = f.openWrite(mode: FileMode.append); slink.write('$value\n'); // await fs.writeAsString('$value'); setState(() { value = ''; }); slink.close(); } catch (e) { // 寫入錯誤 print(e); } } /** * 讀取本地文件的內容 */ void _readContent() async { File file = await _getLocalFile(); // 從文件中讀取變量做爲字符串,一次所有讀完存在內存裏面 String contents = await file.readAsString(); setState(() { allText = contents; }); } // 清空本地保存的文件 void _clearContent() async { File f = await _getLocalFile(); await f.writeAsString(''); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('demo'), ), body: ListView( children: <Widget>[ Container( padding: EdgeInsets.all(8.0), child: Row( children: <Widget>[ Expanded( child: Container( margin: EdgeInsets.only(right: 16.0), child: TextField( controller: TextEditingController( text: value, ), onChanged: (String v) { value = v; }, onSubmitted: (String r) { value = r; }, ), ), ), RaisedButton( color: Theme.of(context).primaryColor, onPressed: _saveValue, child: Text('保存'), ), ], ), ), Container( child: Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ RaisedButton( color: Theme.of(context).accentColor, onPressed: _readContent, child: Text('獲取本地數據'), ), RaisedButton( color: Colors.red, textColor: Colors.white, onPressed: _clearContent, child: Text('清空本地數據'), ), ], ), Container( padding: const EdgeInsets.all(16.0), child: Text('''$allText'''), ), ], ), ), ], ), ); } }