Home > Blockchain >  Casting value results in, type 'Null' is not a subtype of type 'int' in type cas
Casting value results in, type 'Null' is not a subtype of type 'int' in type cas

Time:12-23

I'm going through a tutorial on Flutter and am receiving a run-time error, but I'm not clear why.

The error I'm receiving is, type 'Null' is not a subtype of type 'int' in type cast. However, the value of the variable generating this error isn't null (which is the case for the other entries in SO which is why I feel this is a new question worth posting). I've verified that a couple of ways.

  1. It is a hard-coded value. It is never given the opportunity to be null.
  2. The IDE is showing the value as 10 when the error is thrown.

I was wondering if the error was maybe happening somewhere else, even with IntelliJ showing it occurring on that specific line, but removing the cast from the line that the IDE is indicating as throwing the error removes the error. I've also restarted the IDE, just in case it was one of those fun scenarios that arise occasionally :^).

To be clear, there are some ways that I can remove the error, such as removing the cast or not implementing null-safety, but that's not my goal. I'm just trying to understand why the error is being thrown in the first place when from my Flutter newbie perspective the value being cast isn't null at the time the error is being thrown.

Let me know if there is some other relevant information I can provide to better clarify the situation. I didn't want to provide all the files because I thought that would be too much.

Thank you in advance for any insights you can give.

pubspec.yaml

environment:
  sdk: '>=2.18.6 <3.0.0'

main.dart

import 'package:flutter/material.dart';

import './quiz.dart';
import './result.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppSate();
    //throw UnimplementedError();
  }
}

class _MyAppSate extends State<MyApp> {
  static const _questions = [
    {
      'questionText': 'What\'s your favorite color?',
      'answers': [
        {'text': 'Black', 'score': 10},
        {'text': 'Red',   'score': 5},
        {'text': 'Green', 'score': 3},
        {'text': 'White', 'score': 1},
      ]
    },
    {
      'questionText': 'What\'s your favorite animal?',
      'answers': [
        {'text': 'Rabbit',   'score': 10},
        {'text': 'Dog',      'score': 5},
        {'text': 'Elephant', 'score': 3},
        {'text': 'Lion',     'score': 1},
      ]
    },
    {
      'questionText': 'Who\'s your favorite instructor?',
      'answers': [
        {'text': 'Max',    'score': 10},
        {'text': 'Ann',    'score': 5},
        {'text': 'Fred',   'score': 3},
        {'text': 'Grimal', 'score': 1},
      ]
    }
  ];

  int _questionsIndex = 0;
  int _totalScore = 0;

  void _resetQuiz() {
    setState(() {
      _questionsIndex = 0;
      _totalScore = 0;
    });
  }

  void _answerQuestion(int score) {
    _totalScore  = score;

    if (_questionsIndex < _questions.length) {
      setState(() {
        _questionsIndex = _questionsIndex   1;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('My First App'),
            ),
            body: _questionsIndex < _questions.length
                ? Quiz(answerQuestion: _answerQuestion, questions: _questions, questionIndex: _questionsIndex)
                : Result(_totalScore, _resetQuiz)));
  }
}

quiz.dart

import 'package:flutter/material.dart';

import './question.dart';
import './answer.dart';

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final Function answerQuestion;

  const Quiz({required this.questions, required this.answerQuestion, required this.questionIndex});

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Question(questions[questionIndex]['questionText'] as String),
      ...(questions[questionIndex]['answers'] as List<Map<String, Object>>).map((answer) {
        return Answer(() => answerQuestion(answer['score']) as int, answer['text'] as String);
      }).toList()
    ]);
  }
}

The error occurs within quiz.dart on the following line when casting answer['score']) as int:

return Answer(() => answerQuestion(answer['score']) as int, answer['text'] as String);

enter image description here

CodePudding user response:

It seems like you misplaced as int, try this:

return Answer(() => answerQuestion(answer['score'] as int), answer['text'] as String);
  • Related