如何在 Flutter Mobile App 中加载和查询本地 json 数据
How can I to load and query local json data in Flutter Mobile App
这是我的 key:value 配对本地 json。我需要加载,稍后我需要用于查询。
那么,如何在 Flutter Mobile App 中加载和查询本地 json 数据呢?
{
"currency.01": "United State USD",
"currency.17": "British Pound GBP",
"currency.33": "Euro EUR",
}
将您的 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 and then you have a lot of search methods like the where 方法
rootBundle 通常只是答案的一部分。我也会 json 解码为 return 实际的 json 格式。
import 'dart:convert';
import 'package:flutter/services.dart';
Future<String> loadAsset() async {
return jsonDecode(await rootBundle.loadString('assets/config.json'));
}
然后在您的 main 上,您现在可以将其加载到 List<dynamic>
列表格式的 json 对象。
List<dynamic> response;
response = loadAsset();
然后从这里您现在可以通过
访问您的值
print(response['currency.01']);
输出:美国美元
这是我的 key:value 配对本地 json。我需要加载,稍后我需要用于查询。 那么,如何在 Flutter Mobile App 中加载和查询本地 json 数据呢?
{
"currency.01": "United State USD",
"currency.17": "British Pound GBP",
"currency.33": "Euro EUR",
}
将您的 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 and then you have a lot of search methods like the where 方法
rootBundle 通常只是答案的一部分。我也会 json 解码为 return 实际的 json 格式。
import 'dart:convert';
import 'package:flutter/services.dart';
Future<String> loadAsset() async {
return jsonDecode(await rootBundle.loadString('assets/config.json'));
}
然后在您的 main 上,您现在可以将其加载到 List<dynamic>
列表格式的 json 对象。
List<dynamic> response;
response = loadAsset();
然后从这里您现在可以通过
访问您的值print(response['currency.01']);
输出:美国美元