【问题标题】:How can I to load and query local json data in Flutter Mobile App如何在 Flutter Mobile App 中加载和查询本地 json 数据
【发布时间】:2018-12-23 22:07:41
【问题描述】:

这是我的 key:value 配对的本地 json。我需要加载,稍后我需要用于查询。 那么,如何在 Flutter Mobile App 中加载和查询本地 json 数据呢?

{
  "currency.01": "United State USD",
  "currency.17": "British Pound GBP",
  "currency.33": "Euro EUR",
}

【问题讨论】:

标签: json load flutter


【解决方案1】:

将您的 JSON 文件添加到 pubspec.yaml

  assets:
    - assets/config.json

然后你可以使用rootBundle来加载它

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

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}

也看看这个full example 并用于查询将您的 JSON 数据转换为 LIST,然后您有很多搜索方法,例如 where 方法

【讨论】:

  • 我的值为“01”,所以我也需要进行查询。我需要更改我的 json 数据,或者如果您知道如何使用现有数据进行查询,我将不胜感激。
  • 谢谢@Raouf,我会测试一下。
  • 谢谢!对我帮助很大。
【解决方案2】:

rootBundle 通常只是答案的一部分。我也会做 jsonDecode 来返回一个实际的 json 格式。

import 'dart:convert';
import 'package:flutter/services.dart';

Future<String> loadAsset() async {
  return jsonDecode(await rootBundle.loadString('assets/config.json'));
}

然后在您的主服务器上,您现在可以将其加载到 List&lt;dynamic&gt; 以获取列表格式的 json 对象。

List<dynamic> response;
response = loadAsset();

然后您现在可以从这里访问您的值,

print(response['currency.01']);

输出:美国美元

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2017-05-04
    • 2020-10-15
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多