0

So I am going to create a quiz app but while I run it, I get the following error

'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 :)

Here Is image of Error

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',
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}`
Bruno
  • 3,872
  • 4
  • 20
  • 37
  • Look in the log for the complete stacktrace in the log so you have a better idea which `Text` is causing the problem – Claudio Redi Jun 19 '20 at 11:16

3 Answers3

0

Not a flutter guy. But I'll try to help you. If you look into flutter source and search your error message you'll get a clue what to do. So at text.dart we can find that dart check that you fill data field with a String when you call a constructor. So my bet is that you misplace toString here mydata[0][i.toString()]

vsenik
  • 518
  • 5
  • 12
0

Text widget needs a string to be initialized. As vsenik mentioned, you are probably giving a null instead of string to a text widget. The problem is in one of the below lines.

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

mydata[0][i.toString()]

You could use debug or insert a print statement before these lines.

yed2393
  • 262
  • 1
  • 12
  • D/EGL_emulation( 4327): eglMakeCurrent: 0x9d705480: ver 2 0 (tinfo 0x9d703330) I/flutter ( 4327): [8, 0, 7, 5, 2, 1, 3, 6, 9, 4] I/flutter ( 4327): Tomorrow I/flutter ( 4327): Tomorrow I/flutter ( 4327): Tomorrow is equal to Tomorrow i got this output when i use these print statement and after that same error will happens – Akash Kumar Jun 20 '20 at 02:11
0

I think Yalin is perfectly right, but I would add: Dart has some very useful operators to prevent that kind of errors, which can be catastrofic on real world usage. You can check them here. In particular you could use

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

to prevent this kind of problem when an object is null

Javierd98
  • 708
  • 9
  • 27
  • Yeah that resolve but another error is there like The method '[]' was called on null. Receiver: null Tried calling: []("a") – Akash Kumar Jun 20 '20 at 02:53