In SummaryItem(code bellow) when i tried to cast the question_index as an int, it’s showing me an error saying type ‘Null’ is not a subtype of type ‘int’ in type cast. In QuestionIdentifier(photo bellow), question_index is set as an int. Why it’s showing me this errors?
import 'package:adv_basics/question_identifier.dart';
import 'package:flutter/material.dart';
class SummaryItem extends StatelessWidget {
final Map<String, Object> iconData;
const SummaryItem(this.iconData, {super.key});
@override
Widget build(BuildContext context) {
final isCorrectAnswer =
iconData["correct-answer"] == iconData["user-answer"];
return Row(
children: [
QuestionIdentifier(
correctAnswer: isCorrectAnswer,
questionIndex: iconData["question-index"] as int,
),
const SizedBox(width: 5),
Expanded(
child: Column(
children: [
Text(
iconData["question"] as String,
),
Text(iconData["correct_answer"] as String),
Text(iconData["user_answer"] as String),
],
),
)
],
);
}
}
2
Answers
You see that error because the value of
iconData["question-index"]
isnull
.Approach 1: You can use the null-aware operator
?
.with this if the value of
iconData["question-index"]
isnull
, it will not throw an error.also make
questionIndex
filed nullable inQuestionIdentifier
class.Approach 2: Before passing
iconData["question-index"]
to new child widget that is not designed for null-able arguments, you should check its value to ensure is is notnull
value.iconData["question-index"] is null