如何在Flutter中读取和写入文本文件 [英] How to read and write a text file in Flutter
本文介绍了如何在Flutter中读取和写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您如何从文件读取文本并将文本写入文件?
How do you read text from a file and write text to a file?
我一直在学习如何在文件中读取和写入文本。 。我发现了另一个有关从资产读取的问题,但这并不相同。我将从我从文档中学到的答案添加到下面。
I've been learning about how to read and write text to and from a file. I found another question about reading from assets, but that is not the same. I will add my answer below from what I learned from the documentation.
推荐答案
设置
在 pubspec.yaml
中添加以下插件:
dependencies:
path_provider: ^0.4.1
将版本号更新为< a href = https://pub.dartlang.org/packages/path_provider rel = noreferrer>当前。
并将其导入到您的
import 'package:path_provider/path_provider.dart';
您还必须导入 dart:io
使用 File
类。
import 'dart:io';
写入文本文件
Writing to a text file
_write(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
await file.writeAsString(text);
}
从文本文件读取
Reading from a text file
Future<String> _read() async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
return text;
}
注释
- 您还可以使用
join(directory.path,'my_file.txt')
获取路径字符串,但是您需要导入'package:path / path.dart'
。 - Flutter的读写文件官方文件
- You can also get the path string with
join(directory.path, 'my_file.txt')
but you need to import'package:path/path.dart'
. - Flutter's Official Documentation of Reading and Writing Files
Notes
这篇关于如何在Flutter中读取和写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文