简体   繁体   English

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

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

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

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= [];我想初始化列表以包含所有“答案”数字,以便当列表初始化为 List answerlist= [];

Thanks for any help!谢谢你的帮助!

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 来处理这个(简单的方法),在某些情况下你没有answer ,因为我使用默认值 0,

Model Class 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更像是解析 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检查dartPad

check this below it may help you,在下面检查它可能会对您有所帮助,

DataModel,数据模型,

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
      }
    ]
  });

To get List of answer number from ClassModel,要从 ClassModel 中获取答案编号列表,

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

or或者

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

To get object value from Class using list builder,要使用列表生成器从 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 
    );
  },
)

you can do like this你可以这样做

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

and the result as follow:结果如下:

1
2
1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从列表中查找值<map<string, object> > 在飞镖(扑)? </map<string,> - How to find a value from List<Map<String, Object>> in dart(flutter)? 如何建立清单 <String> 从清单中 <Map<String, String> &gt;在Dart中? - How to create a List<String> from a List<Map<String, String>> in Dart? Dart/Flutter 如何初始化地图内的列表? - Dart/Flutter How to initialize a List inside a Map? 如何在 Dart/Flutter 中初始化文件类型列表 - How Initialize a list of type File in Dart/Flutter 飞镖/颤振:如何在 dart 中将字符串列表转换为 Map - dart/flutter : How to convert List of String into Map in dart 如何在没有构造函数的情况下初始化自定义列表 object [Dart/Flutter] - How to initialize list of custom object with no constructor [Dart/Flutter] 列表<map<string,dynamic> &gt; 列出<string> Dart </string></map<string,dynamic> - List<Map<String,dynamic>> to List<String> Dart 转换 Map<string, object> 列出<widget>在 flutter、dart</widget></string,> - Converting Map<String, Object> to List<Widget> in flutter, dart 如何获取某些值的值作为类型<string>哪个在 Dart/Flutter 的列表中的 Map 内?</string> - how to get values of some values as type<String> which is inside a Map inside List in Dart/Flutter? 如何 model class 以序列化 Dart Z497031794414A553B435F90151ZAC<string, list> ) 进入 Flutter 中的 JSON?</string,> - How to model class in order to serialize Dart Object (Map<String, List>) into JSON in Flutter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM