首页 > 解决方案 > 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
                      )
                    ]
                )
            )
        )
    );
  }


}

标签: jsonflutterdart

解决方案


由于您使用的是 a StatefulWidget,因此您需要使用该setState()方法来更新变量,即使您在initState. 您必须这样做的原因是您使用的是异步数据。initState不会等待数据,因此您必须自己更新状态。更新状态后,它将build再次调用该方法并重建小部件,您的Text小部件将使用test变量中的新值。

此外,从newDart 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;
    });
  }

推荐阅读