Flutter - 从资产中读取文本文件 [英] Flutter - Read text file from assets

查看:36
本文介绍了Flutter - 从资产中读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件 (.txt),我希望将其作为资产,以便稍后扫描.

I have a text file (.txt) that I'd like to be an asset that I can scan in later.

在 pubspec.yaml 中,我确保:

In the pubspec.yaml, I've made sure that:

flutter:
  assets:
    - res/my_file.txt

存在.该文件位于我创建的 res/ 文件夹中,与 lib/android/ios/

exists. The file resides in the res/ folder that I made, on the same level as lib/android/ and ios/

我正在尝试从自定义类而不是小部件读取文件.

I'm trying to read the file from a custom class, not a widget.

根据文档,我将使用此导入:

According to the documentation, I'm to use this import:

import 'package:flutter/services.dart' show rootBundle;

然后像这样开始阅读:

/// Assumes the given path is a text-file-asset.
Future<String> getFileData(String path) async {
  return await rootBundle.loadString(path);
}

要获取实际数据,请执行以下操作:

And to get the actual data, do:

String data = await getFileData(fileName);

但是,当我使用像 'assets/res/my_file.txt' 这样的 fileName 时,出现错误:无法加载资产:assets/res/my_file.txt.

However, when I use a fileName like 'assets/res/my_file.txt', I get an error: Unable to load asset: assets/res/my_file.txt.

还值得注意的是,我正在尝试通过单元测试来做到这一点.关于如何正确执行此操作的任何想法?谢谢!

It's also worth noting that I'm trying to do this from a unit test. Any ideas on how to properly do this? Thanks!

推荐答案

文件夹名称assets"不是神奇地添加的.更新您的 pubspec.yaml 以包含资产的完整路径.

The folder name "assets" isn't magically added. Update your pubspec.yaml to include the full path to the asset.

flutter:
  assets:
    - assets/res/my_file.txt

这篇关于Flutter - 从资产中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆