Home > Back-end >  Unexpected Null value in list type of strings
Unexpected Null value in list type of strings

Time:04-16

I used ! for null safety. But I am Getting unexpected null value error. When I don't use ! it's show me expected a value of type 'List' but got one of type Null. Where I should change my code? In the quiz.dart file I am facing the problem. Here is my main.dart file

import 'package:flutter/material.dart';
import 'package:quiz_app/answer.dart';
import 'package:quiz_app/question.dart';
import 'package:quiz_app/quiz.dart';
import 'package:quiz_app/result.dart';

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

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

class _MyAppState extends State<MyApp> {
  final _questions = const [
    {
      'questionText': 'What\'s your favorite color?',
      'answer': ['Red', 'Yellow', 'Black', 'Brown']
    },
    {
      'questionText': 'What\'s your favorite animal?',
      'answer': ['Cow', 'Goat', 'Camel', 'BUffalo']
    },
    {
      'questionText': 'Who\'s your favorite instructor?',
      'answer': ['Saif', 'Salauddin', 'Linkon', 'Rifat']
    },
  ];
  var _questionIndex = 0;

  void _answerQuestion() {
    setState(() {
      _questionIndex = _questionIndex   1;
    });
    print(_questionIndex);
    if (_questionIndex < _questions.length) {
      print("We have more questions!");
    } else {
      print("No more questions!");
    }
  }

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

Here is quiz.dart file where I am facing the problem.

    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<String>).map((answer) {
          return Answer(answerQuestion, answer);
        }).toList()
      ],
    );
  }
}

CodePudding user response:

I believe the error you are getting is on this line: ...(questions[questionIndex]['answers']! as List<String>).map((answer) {

The problem is that you typed answers instead of answer so you are getting a null value.

The ! does not provide any null safety, what it does is tell Dart that you are sure this value will never be null -- if it does end up being null then you will have an error.

A null safety operator would be ?? which lets you specific a default value in case there is a null. You could do something like:

questions[questionIndex]['questionText'] ?? "No more questions"


On another note, to make you code a little cleaner by just providing your Quiz object with the question and answers and not making it do the indexing part:

 body: _questionIndex < _questions.length
              ? Quiz(
                  questions: _questions[questionIndex],
                  answerQuestion: _answerQuestion[questionIndex])

CodePudding user response:

There is a typo in your quiz.dart file. While you're mapping the questions array to the Question widget, you're supposed to access the answer key, instead, you're trying to a non-existent key named answers.

        ...(questions[questionIndex]['answers']! as List<String>).map((answer) {

You can use the ?? null safe operator instead of !, as ?? helps to provide a null safe value if the value is null. Whether, ! can through exception if the regarding value is null somehow. Use the ! operator if you're 100% sure of data null safety.

Hope you'll find the typo. Happy coding.

  • Related