JSON.DECODE 返回空值,颤振

时间:2021-05-06 07:25:02

标签: json flutter flutter-futurebuilder

我正在尝试创建一个测验应用程序,在其中创建卡片,例如当用户单击特定卡片时,它将被重定向到该测验页面。

这里是我试图获取 json 文件数据的地方,这是测验问题

class getjson extends StatelessWidget {
 
  @override
  Widget build(BuildContext context) {
    
    return FutureBuilder(
      future:DefaultAssetBundle.of(context).loadString("assets/questions/generalQ.json"),
        builder: (context, snapshot) {
        List mydata = json.decode(snapshot.data.toString());
        print(mydata);
        if (mydata == null) {
          return Scaffold(
            body: Center(
              child: Text(
                "Loading",
              ),
            ),
          );
        } else {
          return quizpage();
        }
      },
    );
  }
}


class quizpage extends StatefulWidget {
  @override
  _quizpageState createState() => _quizpageState();
}

class _quizpageState extends State<quizpage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

在这里我创建了卡片小部件

Widget customcard(String langname, String image, String des){
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 20.0,
        horizontal: 30.0,
      ),
      child: InkWell(
        onTap: (){
          Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=>getjson(),));
        },

我在 onTap 上调用 getjson 类。

当我运行应用程序时,点击卡片它显示我“正在加载”,它在 getjson 类的“mydata”上返回 null。

怎么解决?为什么它在 mydata 上返回 null?请帮忙!

JSON 文件:

[
    {
        "1": "What is the world's most populated country?",
        "2": "Each year World Red Cross and Red Crescent Day is celebrated on",
        "3": "The ozone layer restricts"
    },
    {
        "1": {
            "a": "Russia",
            "b": "China",
            "c": "USA"
        },
        "2": {
            "a": "May 8",
            "b": "May 18",
            "c": "April 28"
           
        },
        "3": {
            "a": "Visible light",
            "b": "Ultraviolet radiation",
            "c": "Infrared radiation"
        }
    }
]

1 个答案:

答案 0 :(得分:0)

其实很简单,你说你的 list = a Future 。当您执行 json.decode(snapshot.data) 时,您的 futureBuilder 的 Future 尚未完成,因此当时的 mydata 是 snapshot.data 为空。你应该写:

if(snapshot.ConnectionState == ConnectionState.done){
   List mydata = json.decode(snapshot.data.toString());
   return quizpage();

}else{
return Scaffold(
           body: Center(
             child: Text(
               "Loading",
             ),
           ),
         );
}