如何使用Flutter在Firestore中检索数组索引中的多个字段

时间:2020-04-02 02:34:59

标签: firebase flutter dart google-cloud-firestore

在下面的链接中,我在Firestore中有一些数据。

我的Firestore结构:

enter image description here

我在pointingReminderTime字段中有一个数组。这些索引中的每一个都有MedicationName,notificationType和time。我有一个称为“查看提醒”的功能,该功能向我的用户显示他们之前设置的所有提醒。我希望MedicationName,notificationType和时间以字符串形式传递,并且用户能够看到他们的提醒。

这是我写的一些代码片段

ViewAppointmentReminders.dart

            ListView.builder(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: user.appointmentName.length,
              itemBuilder: (BuildContext context, int index) {
                return appointmentDataitems(user.appointmentName[index],context);
              },
            ),


//List tile for appointment name and then appointment value
Container appointmentDataitems(String appointmentName, BuildContext context) {
  return Container(
    height: 40.0,
    child: ListTile(
      leading: Text(
        "Appointment name:",
      ),
      trailing: Text(
        appointmentName,
      ),
    ),
  );
}

user.dart

class User 
{
  final List<dynamic> appointmentName;

  User(
      {
      this.appointmentName,
      });
}

因此,总而言之,我希望使用Flutter动态显示上面的数据,以便用户查看他们的约会/用药提醒

谢谢!

1 个答案:

答案 0 :(得分:0)

您的用户任命模型如下:

class User{
  List<Appointment> appointments;
  User({this.appointments});

  Map<String, dynamic> toJson() => {
    "appointmentReminderTime": this.appointments
  };


  User.fromJson(Map jsonMap)
      : appointments =   (jsonMap['appointmentReminderTime'] as List)
      ?.map((i) => Appointment.fromJson(i))
      ?.toList();

}

class Appointment {
  final String medicationName;
  final String notificationType;
  final Timestamp time;

  const Appointment(this.medicationName, this.notificationType,this.time);

  Map<String, dynamic> toJson() => {
    "MedicationName": this.medicationName,
    "notificationtype": this.notificationType,
    "time": this.time
  };

  Appointment.fromJson(Map jsonMap)
      : medicationName = jsonMap['MedicationName'],
        notificationType = jsonMap['notificationtype'],
        time = jsonMap['time'];
}

您将从类型为 User 的Firestore中获取数据,然后这就是在UI中显示它们的方式。

ListView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
           itemCount: user.appointments.length,
               itemBuilder: (BuildContext context, int index) {
                   return appointmentDataitems(user.appointments[index],context);
                    },
      ),


//List tile for appointment name and then appointment value
Container appointmentDataitems(Appointment appointment, BuildContext context) {
  return Container(
    height: 40.0,
    child: ListTile(
      leading: Text(
        appointment.medicationName,
      ),
      trailing: Text(
        appointment.notificationType,
      ),
    ),
  );
}