Himanshu Rahi
Himanshu Rahi

Reputation: 301

The argument type 'Object?' can't be assigned to the parameter type 'num' in flutter

Am new in flutter actually am trying to make a simple app. which basically calculate my score. for that i created an question object with score property, here when i try to add totalscore with score at specific index in questions array am getting error saying The argument type 'Object?' can't be assigned to the parameter type 'num'. How can i resolve this.

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

Upvotes: 0

Views: 260

Answers (1)

Mayank
Mayank

Reputation: 1993

You get this error, because questions[qindex]['score'] can return null if the key score doesn't exist, but if you're sure that the it exists, you can do:

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

Upvotes: 1

Related Questions