How can I resolve " The argument type 'Object?' can't be assigned to the parameter type 'String' "?

Viewed 127

This how I have defined my List :

final   _question = [
    {
      'questionText': ' what\'s your favourite color?',
      'answers': [
        {'text': 'Black', 'score': '10'},
        {'text': 'Green', 'score': '80'},
        {'text': 'Blue', 'score': '147'},
        {'text': 'Yellow', 'score': '60'},
      ]
    },
    {
      'questionText': 'what\'s your favourite animal?',
      'answers': [
        {'text': 'Rabbit', 'score': '10'},
        {'text': 'Tiger', 'score': '10'},
        {'text': 'Elephant', 'score': '10'},
        {'text': 'Lion', 'score': '10'},
      ]
    },
];

and then I called the list to extract the 'text' and the 'Score ' by converting the map to list

Question(question[questionindex]['questionText']),
...(question[questionindex]['answers'] as List<Map<String,Object>>).map((answer) {
  return Answer(() => answerQuestion(answer['Score']), answer['text']);
}).toList(),

but I got this error " The argument type 'Object?' can't be assigned to the parameter type 'String' ".

2 Answers

Why not change it to dynamic, also note that it's a lower case s in score:

Question(question[questionindex]['questionText']),
...(question[questionindex]['answers'] as List<Map<String,dynamic>>).map((answer) {
  return Answer(() => answerQuestion(int.parse(answer['score'].toString())), answer['text'].toString());
}).toList(),

You can simply cast it into a List:

final Map currentQuestion = question[currentQuestion];
Question(currentQuestion['questionText'] as String),
...(currentQuestion['answers'] as List).map((answer) {
  return Answer(() => answerQuestion(answer['score'] as String), answer['text'] as String);
}).toList(),

I don't know if you're retrieving this data as a JSON from a server, but to avoid these unnecessary casts, just convert these inner maps into classes. You can also take a look at this tutorial provided by Dart that allows you to use jsonDecode to convert the maps.

class Answer {
  final int score;
  final String text;

  const Answer(this.score, this.text);
}

class Question {
  final String text;
  final List<Answer> answers;

  const Question({required this.text, required this.answers});
}

Declare your questions like this:

const List<Question> questions = [
  Question(text: "Who's Joe?", answers: [
    Answer(0, "Mama"), Answer(100, "Biden"), Answer(20, "Doe")
  ],
  Question(text: "What's Ligma?", answers: [
    Answer(0, "Balls"), Answer(20, "Nuts"), Answer(100, "Sigma"),
  ],
];

and access it like that:

final Question question = questions[questionIndex];
QuestionWidget(question),
...question.answers.map((answer) {
  return AnswerWidget(() => answerQuestion(answer.score), answer.text);
}).toList(),
Related