詳解Flutter如何讀寫文本文件
介紹
文本文件(具有 .txt擴展名)廣泛用于持久存儲信息,從數(shù)字數(shù)據(jù)到長文本。今天,我將介紹 2 個使用此文件類型的 Flutter 應(yīng)用程序示例。
第一個示例快速而簡單。它僅使用 rootBundle(來自 services.dart)從 assets 文件夾(或根項目中的另一個文件夾)中的文本加載內(nèi)容,然后將結(jié)果輸出到屏幕上。當(dāng)您只需要讀取數(shù)據(jù)而不需要寫入數(shù)據(jù)時,這很有用。
第二個例子稍微復(fù)雜一點。它不僅可以讀取用戶輸入的內(nèi)容,還可以將用戶輸入的內(nèi)容寫入文本文件。您將學(xué)習(xí)如何使用File 異步方法, 包括readAsString和writeAsString。
示例 1:加載內(nèi)容
預(yù)覽
此示例包含一個文本小部件和一個浮動按鈕。當(dāng)這個按鈕被按下時,函數(shù) _loadData將被觸發(fā)并從文件中加載內(nèi)容。
將文本文件添加到您的項目中
在項目根目錄的資產(chǎn)文件夾中創(chuàng)建一個名為data.txt的新文本文件(如果尚不存在,則創(chuàng)建一個),并向其添加一些虛擬內(nèi)容,如下所示:
個人簡介:華為云享專家,InfoQ簽約作者,51CTO博客首席體驗官,專注于前端技術(shù)的分享,包括Flutter,小程序,安卓,VUE,JavaScript。如果你迷茫,不妨來瞅瞅碼農(nóng)的軌跡,
不要忘記在pubspec.yaml文件中注冊assets文件夾:
flutter: assets: - assets/
完整代碼
將以下內(nèi)容添加到您的main.dart:
// main.dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show rootBundle; import 'dart:async'; ? void main() { runApp(MyApp()); } ? class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: '堅果', home: HomePage(), ); } } ? class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } ? class _HomePageState extends State<HomePage> { String _data; ? // This function is triggered when the user presses the floating button Future<void> _loadData() async { final _loadedData = await rootBundle.loadString('assets/data.txt'); setState(() { _data = _loadedData; }); } ? @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('堅果'), ), body: Center( child: Container( width: 300, child: Text(_data != null ? _data : 'Nothing to show', style: TextStyle(fontSize: 24)))), floatingActionButton: FloatingActionButton(onPressed: _loadData, child: Icon(Icons.add)), ); } }
示例 2: Reading and Writing
獲取文件路徑
出于安全原因,Android 和 iOS 不允許我們在硬盤驅(qū)動器上的任何位置進行讀寫。我們需要將文本文件保存到Documents目錄中,應(yīng)用程序只能在該目錄中訪問其文件。只有在刪除應(yīng)用程序時才會刪除這些文件。
該文件目錄是NSDocumentDirectory iOS和應(yīng)用程序數(shù)據(jù)在Android上。要獲取該目錄的完整路徑,我們使用path_provider包(這是 Flutter 的官方包)。
通過將path_provider及其版本添加到pubspec.yaml文件的依賴項部分來安裝包,如下所示:
dependencies: path_provider: ^2.0.8
然后運行以下命令:
flutter pub get
并找到如下路徑:
import 'package:path_provider/path_provider.dart'; ? /* .... */ ? Future<String> get _getDirPath async { final _dir = await getApplicationDocumentsDirectory(); return _dir.path; }
示例預(yù)覽
此示例應(yīng)用程序有一個 TextFiled,允許用戶輸入他/她的姓名以寫入文本文件。它還包含一個文本小部件,顯示從該文件讀取的名稱。
完整的代碼和解釋
在此示例中,我們不需要手動創(chuàng)建文本文件并將其添加到項目中。第一次寫入數(shù)據(jù)時會自動創(chuàng)建。
這是我們的main.dart 中的代碼:
// main.dart import 'dart:convert'; ? import 'package:flutter/material.dart'; import 'dart:async'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; ? void main() { runApp(MyApp()); } ? class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: '堅果', home: HomePage(), ); } } ? class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } ? class _HomePageState extends State<HomePage> { // This will be displayed on the screen String _content; ? // Find the Documents path Future<String> _getDirPath() async { final _dir = await getApplicationDocumentsDirectory(); return _dir.path; } ? // This function is triggered when the "Read" button is pressed Future<void> _readData() async { final _dirPath = await _getDirPath(); final _myFile = File('$_dirPath/data.txt'); final _data = await _myFile.readAsString(encoding: utf8); setState(() { _content = _data; }); } ? // TextField controller final _textController = TextEditingController(); // This function is triggered when the "Write" buttion is pressed Future<void> _writeData() async { final _dirPath = await _getDirPath(); final _myFile = File('$_dirPath/data.txt'); // If data.txt doesn't exist, it will be created automatically ? await _myFile.writeAsString(_textController.text); _textController.clear(); } ? @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('堅果'), ), body: Padding( padding: const EdgeInsets.all(20), child: Column( children: [ TextField( controller: _textController, decoration: InputDecoration(labelText: 'Enter your name'), ), ElevatedButton( child: Text('Save to file'), onPressed: _writeData, ), SizedBox( height: 150, ), Text( _content != null ? _content : 'Press the button to load your name', style: TextStyle(fontSize: 24, color: Colors.pink)), ElevatedButton( child: Text('Read my name from the file'), onPressed: _readData, ) ], ), ), ); } }
以上就是詳解Flutter如何讀寫文本文件的詳細內(nèi)容,更多關(guān)于Flutter讀寫文本文件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
利用libmp3lame實現(xiàn)在Android上錄音MP3文件示例
本篇文章主要介紹了利用Lame庫實現(xiàn)在Android上錄音MP3文件示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03Kotlin Channel處理多個數(shù)據(jù)組合的流
最近項目中對 kotlin 的使用比較多。不得不說 kotlin 確實可以極大的提高 android 的開發(fā)效率,channel用于協(xié)程之間的通訊,使用send和receive往通道里寫入或者讀取數(shù)據(jù),2個方法為非阻塞掛起函數(shù),channel是熱流,不管有沒有訂閱者都會發(fā)送2022-11-11Android自定義View——扇形統(tǒng)計圖的實現(xiàn)代碼
本篇文章主要介紹了Android自定義View——扇形統(tǒng)計圖的實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02