Dart:必须向文本小部件提供非空字符串

Dart : A non-null String must be provided to a Text widget

所以我要创建一个测验应用程序,但是当我 运行 它时,我收到以下错误

'pakage:flutter/src/wigets/text.dart': Field assertion : line 298 pos 10 :'data !=null': A non-null String must be provided to a Text widget it is a flutter based code, what are the possible thing i missed ? Can you help me please ! i shall be obliged for this :)

这是错误图片

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',
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}`

不是一个扑朔迷离的人。但我会尽力帮助你。 如果您查看 flutter 源代码并搜索您的错误消息,您就会知道该怎么做。 因此,在 text.dart 处,我们可以发现当您调用构造函数时,dart 检查您是否使用 String 填充了数据字段。 所以我敢打赌你把 toString 放错了地方 mydata[0][i.toString()]

文本小部件需要一个字符串来初始化。正如 vsenik 所提到的,您可能会为文本小部件提供空值而不是字符串。问题出在以下行之一。

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

mydata[0][i.toString()]

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

我觉得亚林说的很对,但我想补充一点: Dart 有一些非常有用的运算符来防止这种错误,这对现实世界的使用来说可能是灾难性的。您可以查看它们 here。特别是你可以使用

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

防止对象为空时出现此类问题