簡體   English   中英

如何從 List 類型初始化 Dart 中的列表<map<string, object> &gt;? </map<string,>

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

我有一些這種形式的數據,如下所示,位於文件的開頭

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,
  },
]

我有一個像這樣的 class

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

我想初始化列表以包含所有“答案”數字,以便當列表初始化為 List answerlist= [];

謝謝你的幫助!

你需要一個 model class 來處理這個(簡單的方法),在某些情況下你沒有answer ,因為我使用默認值 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));
}

更像是解析 json

然后喜歡

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

檢查dartPad

在下面檢查它可能會對您有所幫助,

數據模型,

class QuestionsModel {
  List<Lists> lists;

  QuestionsModel({this.lists});

  QuestionsModel.fromJson(Map<String, dynamic> json) {
    if (json['lists'] != null) {
      lists = new List<Lists>();
      json['lists'].forEach((v) {
        lists.add(new Lists.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.lists != null) {
      data['lists'] = this.lists.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Lists {
  String question;
  List<String> answers;
  int answer;

  Lists({this.question, this.answers, this.answer});

  Lists.fromJson(Map<String, dynamic> json) {
    question = json['question'];
    answers = json['answers'].cast<String>();
    answer = json['answer'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['question'] = this.question;
    data['answers'] = this.answers;
    data['answer'] = this.answer;
    return data;
  }
}
QuestionsModel questionsModel = new QuestionsModel.fromJson({
    "lists": [
      {
        "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
      }
    ]
  });

要從 ClassModel 中獲取答案編號列表,

var answers = questionsModel.lists.map((e) => e.answer);
print("Answers Number : ${answers}"); // (1, 2, 1)

或者

List<int> answers = questionsModel.lists.map((e) => e.answer).toList();
print("Answers Number : ${answers}"); // [1, 2, 1]

要使用列表生成器從 Class 獲取 object 值,

ListView.builder(
  itemCount: questionsModel.lists.length,
  itemBuilder: (BuildContext context, int index) {
    return ListTile(
      title: Text(questionsModel.lists[index].question), // access value like this 
    );
  },
)

你可以這樣做

List<dynamic> rellyAStringList = jsonDecode(jsonEncode(_questions));
print(rellyAStringList[0]);
for(int i=0; i<rellyAStringList.length; i++){
    print(rellyAStringList[i]["answer"]);  
}

結果如下:

1
2
1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM