如何将JSON资产加载到Flutter App中 [英] How to load JSON assets into Flutter App
问题描述
如何将JSON资产加载到Flutter应用程序中?
How do I load a JSON asset into my Flutter app?
我的 pubspec.yaml
文件具有以下:
assets:
- assets/data.json
我一直在尝试加载数据时陷入困境。我尝试了
I keep getting stuck trying to load the data. I tried
final json = JSON.decode(
DefaultAssetBundle.of(context).loadString("assets/data.json")
);
但是我得到了错误
参数类型'Future<不能将String>分配给参数类型'String'。
The argument type 'Future< String>' can't be assigned to the parameter type 'String'.
谢谢!
推荐答案
@Alexandre Beaudet的答案是正确的,但没有给出很多有关正在发生的事情的背景。
@Alexandre Beaudet's answer is correct but doesn't give a lot of context about what is going on.
当您调用 loadString
时,它实际上是一个异步方法调用。您可以知道,因为它返回的是 Future< value>
而不是仅返回的 value
。这意味着它不会立即得到String的结果,但是会在将来的某个时刻出现。
When you're calling loadString
, it's actually an asynchronous method call. You can tell because it returns a Future<value>
rather than just a value
. This means that it doesn't immediately have a result of String, but will at some point in the future.
在Dart中处理异步的主要方法有两种;第一种是使用 async
和 await
,第二种是直接使用期货。请参见异步编程飞镖指南。
There are two main ways of dealing with asynchronicity in Dart; the first being to use async
and await
, the second being to use the futures directly. See the dart guide on Asynchronous Programming.
如果直接使用 future.then
,则可以从常规函数(即initState等)中进行操作。您只需指定回调并在回调中处理结果。
If you use future.then
directly, you can do it from a normal function (i.e. from initState etc). You simply specify the callback and in the callback what to do with the result.
void printDailyNewsDigest() {
final future = gatherNewsReports();
future.then((news) => print(news));
}
如果要使用 await
如@Alexandre所示,您需要将正在使用的功能标记为 async
,即:
If you want to use await
as @Alexandre has illustrated, you need to mark the function you are using it from as async
, i.e.:
Future<Void> printDailyNewsDigest() async {
String news = await gatherNewsReports();
print(news);
}
如果您覆盖某个函数(即initState),则还需要确保不要更改返回值。多数情况下,应该会被dart 2的输入捕获,但是void-> Future似乎不是。
If you override a function (i.e. initState) you also need to make sure you don't change the return value. That should get caught by dart 2's typing most of the time, but void -> Future doesn't seem to be.
最后一件事-如果您使用数据结果构建窗口小部件,您可能需要使用 FutureBuilder 。
One last thing to note - if you're using the result of the data to build widgets, you'll probably want to look at using a FutureBuilder.
这篇关于如何将JSON资产加载到Flutter App中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!