Dart:必须将非null字符串提供给Text小部件

时间:2020-06-19 10:29:02

标签: android flutter dart zappdev

所以我将创建一个测验应用程序,但是在运行它时,出现以下错误

'pakage:flutter / src / wigets / text.dart':字段断言:298行 10:'data!= null':必须将非null字符串提供给Text小部件 这是一个基于波动的代码,我错过了什么呢?你能帮我吗 !我对此有义务:)

这是错误图片

enter image description here

import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:crazyquiz/resultpage.dart';

class getjson extends StatelessWidget {
  String langname;
  getjson(this.langname);
  String assettoload;


  setasset() {
    if (langname == "Funny") {
      assettoload = "assets/funny.json";
    } else if (langname == "General Knowledge") {
      assettoload = "assets/gk.json";
    } else if (langname == "Javascript") {
      assettoload = "assets/js.json";
    } else if (langname == "C++") {
      assettoload = "assets/cpp.json";
    } else {
      assettoload = "assets/linux.json";
    }
  }

  @override
  Widget build(BuildContext context) {

    setasset();

    return FutureBuilder(
      future:
          DefaultAssetBundle.of(context).loadString(assettoload, cache: true),
      builder: (context, snapshot) {
        List mydata = json.decode(snapshot.data.toString());
        if (mydata == null) {
          return Scaffold(
            body: Center(
              child: Text(
                "Loading",
              ),
            ),
          );
        } else {
          return quizpage(mydata: mydata);
        }
      },
    );
  }
}

class quizpage extends StatefulWidget {
  var mydata;

  quizpage({Key key, this.mydata = ""}) : super(key: key);
  @override
  _quizpageState createState() => _quizpageState(mydata);
}

class _quizpageState extends State<quizpage> {
  var mydata;
  _quizpageState(this.mydata);

  Color colortoshow = Colors.indigoAccent;
  Color right = Colors.green;
  Color wrong = Colors.red;
  int marks = 0;
  int i = 1;

  int j = 1;
  int timer = 30;
  String showtimer = "30";
  var random_array;

  Map<String, Color> btncolor = {
    "a": Colors.purple,
    "b": Colors.lightBlueAccent,
    "c": Colors.blueGrey,
    "d": Colors.blueAccent,
  };

  bool canceltimer = false;



  genrandomarray() {
    var distinctIds = [];
    var rand = new Random();
    for (int i = 0;;) {
      distinctIds.add(rand.nextInt(10));
      random_array = distinctIds.toSet().toList();
      if (random_array.length < 10) {
        continue;
      } else {
        break;
      }
    }
    print(random_array);
  }


  @override
  void initState() {
    starttimer();
    genrandomarray();
    super.initState();
  }


  @override
  void setState(fn) {
    if (mounted) {
      super.setState(fn);
    }
  }

  void starttimer() async {
    const onesec = Duration(seconds: 1);
    Timer.periodic(onesec, (Timer t) {
      setState(() {
        if (timer < 1) {
          t.cancel();
          nextquestion();
        } else if (canceltimer == true) {
          t.cancel();
        } else {
          timer = timer - 1;
        }
        showtimer = timer.toString();
      });
    });
  }

  void nextquestion() {
    timer = 30;
    setState(() {
      if (j < 10) {
        i = random_array[j];
        j++;
      } else {
        Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => resultpage(marks: marks),
        ));
      }
      btncolor["a"] = Colors.purple;
      btncolor["b"] = Colors.lightBlueAccent;
      btncolor["c"] = Colors.blueGrey;
      btncolor["d"] = Colors.blueAccent;
    });
    starttimer();
  }

  void checkanswer(String k) {

    if (mydata[2][i.toString()] == mydata[1][i.toString()][k]) {
      [i.toString()][k]);
      marks = marks + 5;

      colortoshow = right;
    } else {

    }
    setState(() {

      btncolor[k] = colortoshow;
      canceltimer = true;
    });


    Timer(Duration(seconds: 1), nextquestion);
  }

  Widget choicebutton(String k) {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 10.0,
        horizontal: 20.0,
      ),
      child: MaterialButton(
        onPressed: () => checkanswer(k),
        child: Text(
          mydata[1][i.toString()][k],
          style: TextStyle(
            color: Colors.white,
            fontFamily: "Alike",
            fontSize: 16.0,
          ),
          maxLines: 1,
        ),
        color: btncolor[k],
        splashColor: Colors.indigo[700],
        highlightColor: Colors.indigo[700],
        minWidth: 200.0,
        height: 45.0,
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    return WillPopScope(
      onWillPop: () {
        return showDialog(
            context: context,
            builder: (context) => AlertDialog(
                  title: Text(
                    "Quizstar",
                  ),
                  content: Text("You Can't Go Back At This Stage."),
                  actions: <Widget>[
                    FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text(
                        'Ok',
                      ),
                    )
                  ],
                ));
      },
      child: Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              flex: 3,
              child: Container(
                padding: EdgeInsets.all(15.0),
                alignment: Alignment.bottomLeft,
                child: Text(
                  mydata[0][i.toString()],
                  style: TextStyle(
                    fontSize: 16.0,
                    fontFamily: "Quando",
                  ),
                ),
              ),
            ),
            Expanded(
              flex: 6,
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    choicebutton('a'),
                    choicebutton('b'),
                    choicebutton('c'),
                    choicebutton('d'),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.topCenter,
                child: Center(
                  child: Text(
                    showtimer.toString(),
                    style: TextStyle(
                      fontSize: 35.0,
                      fontWeight: FontWeight.w700,
                      fontFamily: 'Times New Roman',
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}`

3 个答案:

答案 0 :(得分:0)

不是一个扑朔迷离的家伙。但我会尽力帮助您。 如果您查看抖动源并搜索错误消息,那么您会知道该怎么做。 因此,在text.dart,我们可以找到dart来检查在调用构造函数时是否用String填充数据字段。 所以我敢打赌,您将toString放在这里df = df.groupby(['category', pd.Grouper(freq='h')]).sum() print (df) value value2 value3 category index a 2015-02-03 23:00:00 64.95 129.90 194.85 b 2015-02-04 00:00:00 68.88 137.76 206.64

答案 1 :(得分:0)

文本小部件需要初始化字符串。如vsenik所述,您可能会给文本小部件提供一个null而不是字符串。问题出在以下几行之一。

mydata[1][i.toString()][k]

mydata[0][i.toString()]

您可以在这些行之前使用debug或插入打印语句。

答案 2 :(得分:0)

我认为Yalin是完全正确的,但我要补充一点: Dart有一些非常有用的运算符来防止此类错误,这可能对现实世界的使用造成灾难性影响。您可以检查它们here。特别是您可以使用

mydata[0][i.toString()] ?? "Default text"

防止在对象为空时出现这种问题