flutter - Flutter - 解析本地 JSON 的问题
问题描述
我正在使用这些关于如何解析本地 JSON 文件的说明( https://www.developerlibs.com/2018/11/flutter-how-to-parse-local-json-file-in.html )构建应用程序,但我遇到了错误消息。我仍然是 Flutter 的初学者,因此感谢您的帮助:
l/flutter ( 8377): The following NoSuchMethodError was thrown building FutureBuilder<String>(dirty, state: FutureBuilderState<String>#8f2a5):
l/flutter ( 8377): The method 'cast' was called on null.
l/flutter ( 8377): Receiver: null
l/flutter ( 8377): Tried calling: cast<Map<String, dynamic>>().
代码:
main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_load_local_json/country.dart';
import 'package:flutter_load_local_json/list.dart';
void main() {
runApp(new MaterialApp(
debugShowCheckedModeBanner: false,
theme: new ThemeData(
primaryColor: const Color(0xFF02BB9F),
primaryColorDark: const Color(0xFF167F67),
accentColor: const Color(0xFF167F67),
),
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
List data;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Load local JSON file",
style: new TextStyle(color: Colors.white),),
),
body: new Container(
child: new Center(
// Use future builder and DefaultAssetBundle to load the local JSON file
child: new FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('assets/country.json'),
builder: (context, snapshot) {
List<Country> countries =
parseJosn(snapshot.data.toString());
return !countries.isEmpty
? new CountyList(country: countries)
: new Center(child: new CircularProgressIndicator());
}),
),
));
}
List<Country> parseJosn(String response) {
if(response==null){
return [];
}
final parsed =
json.decode(response.toString()).cast<Map<String, dynamic>>();
return parsed.map<Country>((json) => new Country.fromJson(json)).toList();
}
}
提前致谢
解决方案
在解析 JSON 之前,您必须等待未来完成:
FutureBuilder(
future: DefaultAssetBundle.of(context).loadString('assets/country.json'),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return Text("Loading JSON...")
}
List<Country> countries = parseJson(snapshot.data.toString());
return countries.isNotEmpty
? new CountyList(country: countries)
: new Center(child: Text("Empty list");
}
),
更多信息:https ://api.flutter.dev/flutter/widgets/FutureBuilder-class.html 和https://flutter.dev/docs/development/data-and-backend/json
推荐阅读
- java - 创建 JPA 存储库时出错:EntityPathResolver 不能为空
- http - 如何使用 Go 正确处理 PATCH 请求
- android - 更新数据库中的数据
- r - 如何使用 Kinship2 软件包将多个配偶添加到我的谱系中?
- php - 为什么我在 php 函数中有一个 sintax 错误
- javascript - if else 语句..活动级别的计算
- javascript - react-redux 与 Formik 连接 - 超出最大调用堆栈大小
- c# - 我应该如何使用 mac 在 C# 中设置路径名
- angular - 使用 Karma 测试 Angular 服务中的窗口单击和上下文菜单事件
- java - Java:从由井号标签 (#) 分隔的文件中读取句子