【问题标题】:How to load text file into a String variable in Flutter如何将文本文件加载到 Flutter 中的字符串变量中
【发布时间】:2021-04-26 12:31:49
【问题描述】:

我一直在尝试将文本文件加载到变量中,以便检查用户的输入是否有效。但是,我在尝试将 rootBundle.loadString 函数的输出存储到可用的字符串变量中时遇到了困难,我不知道该怎么做。

我的代码:

Future<String> getFileData(String path) async {
  return rootBundle.loadString(path);
}

String text = getFileData("assets/textfile.txt");

如何将文本文件的内容作为字符串类型存储在变量中?

【问题讨论】:

标签: flutter dart asynchronous


【解决方案1】:

你需要等待loadString方法,它的返回类型是Future&lt;String&gt;。

Future<String> getFileData(String path) async {
  return await rootBundle.loadString(path);
}

String text = await getFileData("assets/textfile.txt");

【讨论】:

  • 当分配给一个字符串时,它说:A value of type 'Future&lt;String&gt;' can't be assigned to a variable of type 'String'.。我将如何使用这个函数的输出?
  • 请查看此官方飞镖文档以了解异步编程。 @12rhombiingridwnocorners dart.dev/codelabs/…
  • 对不起,如果我的问题很愚蠢,但是您如何将 Future 值存储为字符串而不是打印它?
  • 查看该链接并检查Example: asynchronous functions,那里有var order = await fetchUserOrder();。这里 fetchUserOrder() 是 Future 方法。只需阅读整篇文章,您肯定会了解它。
  • 哦,我想我明白我的问题所在了。我需要在异步函数中解析文件的内容,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
相关资源
最近更新 更多