網站首頁 編程語言 正文
介紹
文本文件(具有 .txt擴展名)廣泛用于持久存儲信息,從數字數據到長文本。今天,我將介紹 2 個使用此文件類型的 Flutter 應用程序示例。
第一個示例快速而簡單。它僅使用 rootBundle(來自 services.dart)從 assets 文件夾(或根項目中的另一個文件夾)中的文本加載內容,然后將結果輸出到屏幕上。當您只需要讀取數據而不需要寫入數據時,這很有用。
第二個例子稍微復雜一點。它不僅可以讀取用戶輸入的內容,還可以將用戶輸入的內容寫入文本文件。您將學習如何使用File 異步方法, 包括readAsString和writeAsString。
示例 1:加載內容
預覽
此示例包含一個文本小部件和一個浮動按鈕。當這個按鈕被按下時,函數 _loadData將被觸發并從文件中加載內容。
將文本文件添加到您的項目中
在項目根目錄的資產文件夾中創建一個名為data.txt的新文本文件(如果尚不存在,則創建一個),并向其添加一些虛擬內容,如下所示:
個人簡介:華為云享專家,InfoQ簽約作者,51CTO博客首席體驗官,專注于前端技術的分享,包括Flutter,小程序,安卓,VUE,JavaScript。如果你迷茫,不妨來瞅瞅碼農的軌跡,
不要忘記在pubspec.yaml文件中注冊assets文件夾:
flutter:
assets:
- assets/
完整代碼
將以下內容添加到您的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 不允許我們在硬盤驅動器上的任何位置進行讀寫。我們需要將文本文件保存到Documents目錄中,應用程序只能在該目錄中訪問其文件。只有在刪除應用程序時才會刪除這些文件。
該文件目錄是NSDocumentDirectory iOS和應用程序數據在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;
}
示例預覽
此示例應用程序有一個 TextFiled,允許用戶輸入他/她的姓名以寫入文本文件。它還包含一個文本小部件,顯示從該文件讀取的名稱。
完整的代碼和解釋
在此示例中,我們不需要手動創建文本文件并將其添加到項目中。第一次寫入數據時會自動創建。
這是我們的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,
)
],
),
),
);
}
}
原文鏈接:https://juejin.cn/post/7085367260935618574
相關推薦
- 2023-01-07 Python中導入模塊的幾種方式總結_python
- 2022-06-29 Oracle數據庫之PL/SQL使用流程控制語句_oracle
- 2022-11-10 Flutter?WillPopScope攔截返回事件原理示例詳解_Android
- 2022-05-11 Feign之間的文件傳輸
- 2022-12-01 Apache?Doris?Colocate?Join?原理實踐教程_Linux
- 2022-09-16 C#數據庫操作的示例詳解_C#教程
- 2022-08-23 Pandas?Matplotlib保存圖形時坐標軸標簽太長導致顯示不全問題的解決_python
- 2024-02-29 UNI-APP項目在引用官方提供的Uni-App-Demo實例中的組件時應該注意的問題
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支