Oriol Lopez
Oriol Lopez

Reputation: 369

Assign value to a null value with Flutter

I am having a weird problem.

I am using a JSON (Map<String, dynamic>) object type in order to answer questions in a dynamic way, since there are a lot of questions with different types.

Example: I have a list of questions where the answers can be numbers, strings or booleans.

Here is my problem...

When I have questions where I expect an "int", I get an error saying.

type 'int' is not a subtype of type 'Null' of 'value'

This is basically because I initialize the JSON with the question equal to "null".

List<Map<String, dynamic>> questions = [{ question: 'How old are you?', answer: null }];

But when they answer the question I do something like this:

questions[questionIndex]['answer'] = 20;

For some reason, when I do this, I get the error, saying that the JSON was expecting an Null valuable since I initizlied the answer with "null". How can I change this behaviour in order to be able to assign String, int or Boolean variables in a JSON object that is has been initialized to null?

Thanks friends!

Upvotes: 1

Views: 6585

Answers (1)

julemand101
julemand101

Reputation: 31209

When creating { question: 'How old are you?', answer: null } try specify the precise type you want like <String, dynamic>{ question: 'How old are you?', answer: null }.

void main() {
  List<Map<String, dynamic>> questions = [
    <String, dynamic>{'question': 'How old are you?', 'answer': null}
  ];
  questions[0]['answer'] = 20;
  print(questions); // [{question: How old are you?, answer: 20}]
}

Upvotes: 2

Related Questions