我不知道我能做什么或我做错了什么。所以我想从保存在资产文件夹中的文件中读取一些单词:
我还修改了 pubspec.yaml 文件:
flutter:
uses-material-design: true
assets:
- assets/this.txt
我的代码如下所示:
final String filePath = 'assets/this.txt';
List<String> wordList = [];
try {
final file = File(filePath);
List<String> lines = await file.readAsLines();
final random = Random();
for (int i = 0; i < 4; i++) {
int randomIndex = random.nextInt(lines.length);
wordList.add(lines[randomIndex]);
}
} catch (e) {
print('Error reading file: $e');
}
我仍然收到错误代码:
Error reading file: FileSystemException: Cannot open file, path = 'assets/this.txt' (OS Error: No such file or directory, errno = 2)
不知道我做错了什么:(
解决方案是使用资源包中的方法。
List<String> wordList = [];
try {
String fileContents = await rootBundle.loadString('assets/this.txt');
fileContents = fileContents.toLowerCase();
List<String> lines = fileContents.split('\n');
final random = Random();
for (int i = 0; i < 4; i++) {
int randomIndex = random.nextInt(lines.length);
wordList.add(lines[randomIndex]);
}
} catch (e) {
print('Error reading file: $e');
}