如何将 JSON 资产加载到 Flutter 应用程序中? [英] How to load JSON assets into a Flutter App?

查看:39
本文介绍了如何将 JSON 资产加载到 Flutter 应用程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 JSON 资源加载到我的 Flutter 应用程序中?

How do I load a JSON asset into my Flutter app?

我的 pubspec.yaml 文件包含以下内容:

My pubspec.yaml file has the following:

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<;字符串>'不能分配给参数类型字符串".

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.这意味着它不会立即得到 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 中处理异步性的方法主要有两种;第一个是使用 asyncawait,第二个是直接使用期货.请参阅 有关异步编程的 dart 指南.

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 的打字捕获,但是无效 ->未来似乎没有.

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 应用程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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