【问题标题】:Map an Array of objects from Firebase to List Flutter将一组对象从 Firebase 映射到 List Flutter
【发布时间】:2021-11-16 20:06:24
【问题描述】:

我正在尝试从 Firebase 检索对象数组并将其作为列表存储在 Flutter Object 中。

这是集合,Firebase,

这是模型类

class Merchant {
  String shopName;
  String address;
  String description;
  String thumbNail;
  LatLng locationCoords;

  Merchant( 
      {this.shopName,
      this.address,
      this.description,
      this.thumbNail,
      this.locationCoords});
}


final List<Merchant> merchant = [];      // Map it to This List

我想把它映射到上面的这个列表中

    final List<Merchant> merchant = [];  

【问题讨论】:

  • 您查看过 Flutter 的 Firestore 文档吗?你试过什么?
  • 是的,我似乎不知道如何从文档中映射它

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

首先将此方法添加到您的 Merchant 类中:

Merchant.fromMap(Map<String, dynamic> map) {
    shopName = map['shopName'];
    address = map['address'];
    description = map['description'];
    thumbnail = map['thumbnail'];
    locationCoords = map['locationCoords'];
  }

此方法随后将用于将数据写入 Merchant Class/Struct。

检索数据可能如下所示:

import 'package:cloud_firestore/cloud_firestore.dart';

FirebaseFirestore _firestore = FirebaseFirestore.instance;

CollectionReference merchRef = _firestore.collection('merchants'));


Future<List<Merchant>> getAllMerchants() async {
  List<Merchant> merchantList = [];
  
  await merchRef.get().then((QuerySnapshot querySnapshot) {
    querySnapshot.docs.forEach((doc) {
      Merchant merchant = Merchant.fromMap({
        'shopName': doc['shopname'],
        'address': doc['address'],
        'description': doc['description'],
        'thumbnail': doc['thumbnail'],
        'locationCoords': doc['location'],
      });
      merchantList.add(merchant);
    });
  });

 return merchantList;
}


附: 还没有尝试过,您可能需要对 locationCoords 进行一些解析,因为它是 LatLng 类型。

【讨论】:

  • 对于我使用的位置 LatLng(doc)['latitude'], doc)['longitude']), 现在工作,谢谢
猜你喜欢
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多