为什么dart不断返回类型'List <dynamic>'不是'List <int>'类型的子类型错误?

时间:2020-03-25 10:46:21

标签: list flutter dart widget

通过创建测验应用程序,我几乎完成了Flutter / Dart项目。我面临的唯一挑战的dart文件是我命名的测验文件。下面是确切的代码:

[252, 55, 222, 129, 178, 237, 141, 108, 104, 113, 232, 152, 168, 114, 250, 185, 198, 211, 105, 25, 4, 141, 152, 14, 177, 251, 109, 160, 70, 119, 253, 204, 126, 211, 250, 96, 114, 151, 196, 180, 238, 94, 11, 68, 44, 166, 158, 47]

下面突出显示的代码是我认为我的问题所在:应用程序崩溃并返回此确切错误:

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

class getjson extends StatelessWidget {
  // accept the alphabet as a parameter

  String alphabet;
  getjson(this.alphabet);
  String assettoload;

  // a function
  // sets the asset to a particular JSON file
  // and opens the JSON
  setasset() {
    if (alphabet == "Harafin A") {
      assettoload = "assets/A.json";
    } else if (alphabet == "Harafin B") {
      assettoload = "assets/B.json";
    } else if (alphabet == "Harafin C") {
      assettoload = "assets/C.json";
    } else if (alphabet == "Harafin D") {
      assettoload = "assets/D.json";
    } else if (alphabet == "Harafin F") {
      assettoload = "assets/F.json";
    } else if (alphabet == "Harafin G") {
      assettoload = "assets/G.json";
    } else if (alphabet == "Harafin H") {
      assettoload = "assets/H.json";
    } else if (alphabet == "Harafin I") {
      assettoload = "assets/I.json";
    } else if (alphabet == "Harafin J") {
      assettoload = "assets/J.json";
    } else if (alphabet == "Harafin K") {
      assettoload = "assets/K.json";
    } else if (alphabet == "Harafin L") {
      assettoload = "assets/L.json";
    } else if (alphabet == "Harafin M") {
      assettoload = "assets/M.json";
    } else if (alphabet == "Harafin N") {
      assettoload = "assets/N.json";
    } else if (alphabet == "Harafin R") {
      assettoload = "assets/R.json";
    } else if (alphabet == "Harafin S") {
      assettoload = "assets/S.json";
    } else if (alphabet == "Harafin T") {
      assettoload = "assets/T.json";
    } else if (alphabet == "Harafin U") {
      assettoload = "assets/U.json";
    } else if (alphabet == "Harafin W") {
      assettoload = "assets/W.json";
    } else if (alphabet == "Harafin Y") {
      assettoload = "assets/Y.json";
    } else {
      assettoload = "assets/Z.json";
    }
  }

  @override
  Widget build(BuildContext context) {
    // this function is called before the build so that
    // the string assettoload is available to the DefaultAssetBuilder
    setasset();
    // and now we return the FutureBuilder to load and decode JSON
    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, @required 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;

  // extra varibale to iterate
  int j = 1;
  int timer = 30;
  String showtimer = "30";

  Map<String, Color> btncolor = {
    "a": Colors.indigoAccent,
    "b": Colors.indigoAccent,
    "c": Colors.indigoAccent,
  };

  bool canceltimer = false;

  // overriding the initstate function to start timer as this screen is created
  @override
  var random_array = [1, 2, 3, 4, 5, 6, 7, 8, 9,10];
  void initState() {
//       var random_array;
       var distinctIds = [];
       var rand = new Random();
         for (int i = 0; ;) {
         distinctIds.add(rand.nextInt(12));
           random_array = distinctIds.toSet().toList();
           if(random_array.length <10){
             continue;
           }else{
             break;
           }
         }
    starttimer();
    super.initState();
  }

  // overriding the setstate function to be called only if mounted
  @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() {
    canceltimer = false;
    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.indigoAccent;
      btncolor["b"] = Colors.indigoAccent;
      btncolor["c"] = Colors.indigoAccent;
    });
    starttimer();
  }

  void checkanswer(String k) {
    // in the previous version this was
    // mydata[2]["1"] == mydata[1]["1"][k]
    // which i forgot to change
    // so nake sure that this is now corrected
    if (mydata[2][i.toString()] == mydata[1][i.toString()][k]) {
      // just a print sattement to check the correct working
      // debugPrint(mydata[2][i.toString()] + " is equal to " + mydata[1][i.toString()][k]);
      marks = marks + 10;
      // changing the color variable to be green
      colortoshow = right;
    } else {
      // just a print sattement to check the correct working
      // debugPrint(mydata[2]["1"] + " is equal to " + mydata[1]["1"][k]);
      colortoshow = wrong;
    }
    setState(() {
      // applying the changed color to the particular button that was selected
      btncolor[k] = colortoshow;
      canceltimer = true;
    });

    // changed timer duration to 1 second
    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: "Oswald",
            fontSize: 20.0,
          ),
          maxLines: 2,
        ),
        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(
                    "HausaQuiz",
                  ),
                  content: Text("Ba zaka iya komawa baya ba a daidai nan!"),
                  actions: <Widget>[
                    FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text(
                        'To',
                      ),
                    )
                  ],
                ));
      },
      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: 20.0,
                    fontFamily: "Oswald",
                  ),
                ),
              ),
            ),
            Expanded(
              flex: 6,
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    choicebutton('a'),
                    choicebutton('b'),
                    choicebutton('c'),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.topCenter,
                child: Center(
                  child: Text(
                    showtimer,
                    style: TextStyle(
                      fontSize: 35.0,
                      fontWeight: FontWeight.w700,
                      fontFamily: 'Oswald',
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

“列表”类型不是“列表”类型的子类型**

看看我认为问题出在哪里:

The following assertion was thrown building FutureBuilder<String>(state: _FutureBuilderState<String>#42556):

还要注意,如果我删除var random_array = [1, 2, 3, 4, 5, 6, 7, 8, 9,10]; void initState() { // var random_array; var distinctIds = []; var rand = new Random(); for (int i = 0; ;) { distinctIds.add(rand.nextInt(12)); random_array = distinctIds.toSet().toList(); if(random_array.length <10){ continue; }else{ break; } } 中的整数并像var random_array = [1, 2, 3, 4, 5, 6, 7, 8, 9,10]一样离开,该应用将运行,但是一旦遇到5、6个问题,它将崩溃,请等待几秒钟并继续提出使整个过程迷失的问题。

这正是我要做的事情: 在创建并放入资产文件夹的每个json文件中,我平均有200个问题。我想编写一个可以生成随机问题的代码,例如json文件中的200个问题中的10个随机问题。我想把问题随机化。

0 个答案:

没有答案