Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter error: "The type 'null' is not a subtype of type 'String' in type cast"

hi I’m new to flutter and use BlueStacks as an AVD.I saw this error in BlueStacks.The VS Code does not show any error
.enter image description here

after Running the app i see these messages in Debug Consle:enter image description here
enter image description here

and here is my main.dart code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import 'package:flutter/material.dart';

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final _questions = const [
    {
      'questionText': 'whats ur favorite animal',
      'answers': [
        {'Text': 'khar', 'score': '10'},
        {'Text': 'gaav', 'score': '7'},
        {'Text': 'asb', 'score': '1'},
        {'Text': 'boz', 'score': '3'},
      ],
    },
    {
      'questionText': 'whats ur favorite color',
      'answers': [
        {'Text': 'siah', 'score': '10'},
        {'Text': 'sabz', 'score': '3'},
        {'Text': 'sefid', 'score': '1'},
        {'Text': 'sorkh', 'score': '5'},
      ],
    },
    {
      'questionText': 'whats ur favorite name',
      'answers': [
        {'Text': 'reza', 'score': '1'},
        {'Text': 'reza', 'score': '1'},
        {'Text': 'reza', 'score': '1'},
        {'Text': 'reza', 'score': '1'}
      ],
    },
  ];
  var _questionIndex = 0;
  var _totalScore = 0;

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

  void _answerQuestion(int score) {
    _totalScore = _totalScore + score;

    setState(() {
      _questionIndex = _questionIndex + 1;
    });
    print(_questionIndex);
    if (_questionIndex < _questions.length) {
      print('we have more question!');
    } else {
      print('no more question!');
    }
  }

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

and here is my quiz.dart file :

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;

  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']), answer['text'] as String);
        }).toList()
      ],
    );
  }
}

answer.dart file :

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final VoidCallback selectHandler;
  final String answerText;

  Answer(this.selectHandler, this.answerText);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.blue),
          foregroundColor: MaterialStateProperty.all(Colors.white),
        ),
        onPressed: selectHandler,
        child: Text(answerText),
      ),
    );
  }
}

and result.dart file:

import 'package:flutter/material.dart';

class Result extends StatelessWidget {
  final int resultScore;
  final VoidCallback resetHandler;

  Result(this.resultScore, this.resetHandler);

  String get resultPhrase {
    String resultText;
    if (resultScore <= 8) {
      resultText = 'You are awsome and Bigonah';
    } else if (resultScore <= 12) {
      resultText = 'Bad ni';
    } else if (resultScore <= 16) {
      resultText = 'You are Strange';
    } else {
      resultText = 'Go Doctor!';
    }
    return resultText;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Text(
            resultPhrase,
            style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ),
          ElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.blue),
              foregroundColor: MaterialStateProperty.all(Colors.white),
            ),
            onPressed: resetHandler,
            child: Text('Restart Quiz!'),
          ),
        ],
      ),
    );
  }
}

>Solution :

The error tells you that the following line have an issue:

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

Your error here is that you are reading a value called text from the map but the name of the key in your map is called Text:

...
    {
      'questionText': 'whats ur favorite animal',
      'answers': [
        {'Text': 'khar', 'score': '10'},
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading