首页 > 解决方案 > 参数类型“对象?” 不能在颤振中分配给参数类型“num”

问题描述

我是 Flutter 的新手,实际上是在尝试制作一个简单的应用程序。这基本上计算了我的分数。为此,我创建了一个带有 score 属性的问题对象,在这里,当我尝试在问题数组中的特定索引处添加带有分数的总分时,出现错误说参数类型“对象?” 不能分配给参数类型 'num'。我该如何解决这个问题。

class MyAppState extends State<MyApp> {
  var questions = [
    {
      'questionText': 'This is Question 1',
      'answers': ['a', 'b'],
      'score': 10
    },
    {
      'questionText': 'This is Question 2',
      'answers': ['a', 'b'],
      'score': 15
    },
    {
      'questionText': 'This is Question 3',
      'answers': ['a', 'b'],
      'score': 25
    },
  ];
  int qindex = 0;
  int totalScore = 0;
  void answer() {
  
    setState(() {
      qindex = qindex + 1;
    });
    totalScore += questions[qindex]['score']; //<-- here am getting error.
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(title: Text("App Bar")),
      body: qindex <= questions.length - 1
          ? Column(
              children: [
                Question(questions[qindex]['questionText']),
                ...(questions[qindex]['answers'] as List)
                    .map((ans) => Answer(answer, ans))
              ],
            )
          : Center(
              child: Text(
                "No More Result",
                style: TextStyle(fontSize: 28),
              ),
            ),
    ));
  }
}

标签: flutterdart

解决方案


您会收到此错误,因为如果密钥不存在questions[qindex]['score']可以返回,但如果您确定它存在,您可以执行以下操作:nullscore

totalScore += questions[qindex]['score'] as int;

推荐阅读