gpt4 book ai didi

flutter - 从Firestore将键值对数组加载到Flutter的List中

转载 作者:行者123 更新时间:2023-12-03 02:54:38 25 4
gpt4 key购买 nike

关于将数据从Firestore映射到Flutter中的模型类,需要一些帮助。
我的数据库结构:
enter image description here
我的模型课在下面,

class Exercises {

String difficult, image, time, title;
List<dynamic> MainExercise = [];

Exercises.fromMap(Map<String, dynamic> data){

title = data['title'];
time = data['time'];
difficult = data['difficult'];
image = data['image'];
MainExercise = List<dynamic>.from(data['MainExercise']);

}


}
引发错误
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The getter 'iterator' was called on null.
E/flutter (22059): Receiver: null
E/flutter (22059): Tried calling: iterator
E/flutter (22059): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
我想从 Firestore 中读取 MainExercise 数组(以及其他字符串字段),并将其与我的练习 模型类映射,我将使用该模型来填充列表 View 。

最佳答案

只要数据库中有嵌套的Json对象,就为其创建另一个类,然后在第一类中使用它。
另外,您的类是不完整的,没有构造函数或从jsonMap构造函数返回任何内容。
由于MainExercise字段是List<Map<String,dynamic>>,因此请执行此操作,

class Exercises {

String difficult;
String image;
String time;
String title;
List<MainExercise> mainExercise;

Exercises({this.image, this.title, this.time, this.difficult, this.mainExercise});

Exercises.fromMap(Map<String, dynamic> data){

final String title = data['title'];
final String time = data['time'];
final String difficult = data['difficult'];
final String image = data['image'];
final List<Map<String,dynamic>> mainExercise = data['mainExercise'];

return Exercises(
image : image,
title : title,
time : time ,
difficult : difficult,
mainExercise : ListMainExercise.fromMap(mainExercise);
}

}

class MainExercise {
String exImage;
String exName;
String exTime;

MainExercise({this.exImage, this.exName, this.exTime});

factory MainExercise.fromMap(Map<String, dynamic> data){

final exName = data['exName'];
final exImage = data['exImage'];
final exTime = data['exTime'];

return MainExercise(
exImage: exImage,
exName: exName,
exTime: exTime
);
}
}


class ListMainExercise{
List<MainExercise> listExercise;

ListMainExercise({this.listExercise});

ListMainExercise.fromJson(Map<String,dynamic> data){
(data as List)
?.map(
(e) => e == null ? null : MainExercise.fromJson(e as Map<String, dynamic>))
?.toList()

}
}
另外,建议使用dart约定(例如camelCasing和 factory构造函数)创建fromMap。
编辑:应该解决它,并且还建议使用 json_serializable包,使整个过程变得更加容易。

关于flutter - 从Firestore将键值对数组加载到Flutter的List中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64287105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com