skip to Main Content

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?

enter image description here

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


  1. You see that error because the value of iconData["question-index"] is null.

    Approach 1: You can use the null-aware operator ? .

    QuestionIdentifier(
      correctAnswer: isCorrectAnswer,
      questionIndex: iconData["question-index"] as int?,
    ),
    

    with this if the value of iconData["question-index"] is null, it will not throw an error.

    also make questionIndex filed nullable in QuestionIdentifier 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 not null value.

    Login or Signup to reply.
  2. iconData["question-index"] is null

           QuestionIdentifier(
              correctAnswer: isCorrectAnswer,
              questionIndex: iconData["question-index"] ??0,
            ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search