dart 我想检索存储在firebase中的数据,这些数据存储为数组,然后我需要从firebase中获取数组,并将其存储在flutter中的列表中

toiithl6  于 2022-12-15  发布在  Flutter
关注(0)|答案(1)|浏览(154)

这是我的数据库示例sample of database

我需要获取这些数组并将其存储到列表中

这是我为这些数据创建的模型类

> class ContainerItems {   String Title, time, daytime, iconName;
> 
>   ContainerItems({required this.Title,
>     required this.iconName,
>     required this.time,
>     required this.daytime}); }

并请告诉我如何访问每个单独的项目.在这列表中

请帮帮我

wvt8vs2t

wvt8vs2t1#

首先,我使用模型类创建了一个工厂,以简化将数据库列表的Map<String, dynamic>元素建模为ContainerItems的过程:

class ContainerItems {
  String Title, time, daytime, iconName;

  ContainerItems({
    required this.Title,
    required this.iconName,
    required this.time,
    required this.daytime,
  });

  factory ContainerItems.fromJson(Map<String, dynamic> json) {
    return ContainerItems(
      Title: json['title'] as String,
      time: json['time'] as String,
      daytime: json['daytime'] as String,
      iconName: json['image'] as String,
    );
  }
}

然后,可以使用此方法从数据库中获取List<ContainerItems>结果:

Future<List<ContainerItems>> methodName() async {
  List<ContainerItems> result = [];

  final documentSnapshot = await FirebaseFirestore.instance
      .collection('messdiary')
      .doc('days')
      .get();

  final documentData = documentSnapshot.data() as Map<String, dynamic>;
  final sundayList = documentData["sunday"] as List;

  sundayList.forEach((element) {
    result.add(ContainerItems.fromJson(element as Map<String, dynamic>));
  });

  return result;
}

相关问题