[Solved] How to initialize a list in Dart from type List<Map<String, Object>>?

Question

Asked by Marco G on December 21, 2021 (source).

I have some data in this form as below located at the start of the file

const _questions = [
  {
    'question': 'How long is New Zealand’s Ninety Mile Beach?',
    'answers': [
      '88km, so 55 miles long.',
      '55km, so 34 miles long.',
      '90km, so 56 miles long.'
    ],
    'answer': 1,
  },
  {
    'question':
        'In which month does the German festival of Oktoberfest mostly take place?',
    'answers': ['January', 'October', 'September'],
    'answer': 2,
  },
  {
    'question': 'Who composed the music for Sonic the Hedgehog 3?',
    'answers': [
      'Britney Spears',
      'Timbaland',
      'Michael Jackson',
    ],
    'answer': 1,
  },
]

I have a class like this

class QuestionNumber with ChangeNotifier {
List<int> answerlist= [1, 2, 1];
}

I want to initialise the list to have all of the 'answer' numbers so that when that the list is initialised to List answerlist= [];

Thanks for any help!

Answer

Question answered by Yeasin S (source).

You need a model class to handle this(easy approach), and in some cases you don't have answer filed, for that I'm using default value 0,

Model Class

class Question {
  final String question;
  final List<String> answers;
  final int answer;
  Question({
    required this.question,
    required this.answers,
    required this.answer,
  });

  Map<String, dynamic> toMap() {
    return {
      'question': question,
      'answers': answers,
      'answer': answer,
    };
  }

  factory Question.fromMap(Map<String, dynamic> map) {
    return Question(
      question: map['question'] ?? '',
      answers: List<String>.from(map['answers']),
      answer: map['answer']?.toInt() ?? 0,
    );
  }

  String toJson() => json.encode(toMap());

  factory Question.fromJson(String source) =>
      Question.fromMap(json.decode(source));
}

It is more like parsing json

Then do like

  List<Question> questionlist =
      _questions.map((q) => Question.fromMap(q)).toList();
  List<int> answerlist = [];
  for (final q in questionlist) {
    answerlist.add(q.answer);
  }
  

Check on dartPad

DART FLUTTER
SHARE: