json - Dart 从 Json 中读取
问题描述
Dart 语言的新手并一直在尝试制作一个应用程序,但我已经被这个问题困扰了一段时间,似乎无法解决它。我一直在尝试从 Json 文件中读取内容并使用随机值生成器从 Json 中选择要显示的信息,
前任
姓名:Roxxxer 电子邮件:Roxxxer@hotmail.com
姓名:Roxxxer1 电子邮件:Roxxxer1@hotmail.com
但是每次我尝试显示这些值中的任何一个时,我都会收到此错误:
这是 json 类阅读器(?)
class Recept{
final String title;
final String body;
Recept({this.title, this.body});
factory Recept.fromJson(dynamic json){
return Recept( title: json['title'] as String,
body: json['body'] as String,
);
}
String toString() {
return '{ ${this.title}, ${this.body} }';
}
}
import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:randomfood/Recept.dart';
import 'package:flutter/services.dart';
void main() {
runApp(
new MaterialApp(
home: new AwesomeButton()
)
);
}
class AwesomeButton extends StatefulWidget {
@override
Button createState() => new Button();
}
class Button extends State<AwesomeButton> {
String test;
void onPressed() {
setState(() {
//This is where the random generator goes in and give a new place in the json file
});
}
Future<String> LoadRecipesFromJson() async{
return await rootBundle.loadString('assets/test.json');
}
Future LoadRecipes() async{
String jsonString = await LoadRecipesFromJson();
final jsonResponse = json.decode(jsonString);
Recept recept = new Recept.fromJson(jsonResponse);
String ToString() {
return '${recept.title}';
}
test = ToString();
}
@override
void initState() {
super.initState();
LoadRecipes();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("Random Recipe Generator!"), backgroundColor: Colors.blueGrey),
body: new Container(
child: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new Text(test, style: new TextStyle(color: Colors.black,fontStyle: FontStyle.italic, fontSize: 30.0, fontWeight: FontWeight.bold)),
new Padding(padding: new EdgeInsets.all(50.0)),
new RaisedButton(
child: new Text("Random Recept!", style: new TextStyle(color: Colors.white, fontStyle: FontStyle.italic, fontSize: 20.0)),
color: Colors.blueGrey,
onPressed: onPressed
)
]
)
)
)
);
}
}
解决方案
由于您使用的是 a StatefulWidget
,因此您需要使用该setState()
方法来更新变量,即使您在initState
. 您必须这样做的原因是您使用的是异步数据。initState
不会等待数据,因此您必须自己更新状态。更新状态后,它将build
再次调用该方法并重建小部件,您的Text
小部件将使用test
变量中的新值。
此外,从new
Dart 2.0 开始,关键字是可选的。
更正:您可以将一个函数放在另一个函数中。
Future<void> LoadRecipes() async{
String jsonString = await LoadRecipesFromJson();
final jsonResponse = json.decode(jsonString);
Recept recept = new Recept.fromJson(jsonResponse);
setState(() {
test = recept.title;
});
}
推荐阅读
- selenium - 如何根据测试用例通过百分比设置 Jenkins 作业状态
- blockchain - 为什么 Bitcoin-Qt 和区块链 API 之间的区块链费用存在差异?
- python - 将内容添加到列表
- next.js - 错误“getStaticPaths 只能用于动态页面,不能用于 Next JS”
- producer-consumer - 在生产者/消费者问题的关键部分内循环
- python - 将数据集分布与另一个匹配
- regex - 正则表达式 - 最后一次出现后的所有内容
- javascript - 本机模块的单元测试 - 反应本机应用程序
- php - 有没有办法通过作曲家更新扩展并绕过 Magento2 上的内存限制错误
- flutter - 如何检查小部件是否被删除?