【问题标题】:Save List in Model as Collection in Firestore将模型中的列表保存为 Firestore 中的集合
【发布时间】:2019-01-16 23:38:23
【问题描述】:

我想将我的地址保存在 Firestore 中作为一个集合,而不是一个数组。我该怎么做?

查看代码在firestore中产生的结果。

===

代码:

class User {
  String id;
  String name;
  String email;
  List<Address> address = new List<Address>();

  User({this.id, this.name, this.email, this.address});

  User.fromMap(Map<String, dynamic> map) {
    this.id = map['id'];
    this.name = map['name'];
    this.email = map['email'];

    if (map['address'] == null) {
      this.address = new List<Address>();
    } else {
      this.address= (map['address'] as List).map((i) => Address.fromMap(i)).toList();
    }
  }

  Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'email': email, 'address': address};
  }
}

===

class Address {
  String test;

  Address ({this.test});

  Address.fromMap(Map<String, dynamic> map) {
    this.test = map['test'];
  }

  Map<String, dynamic> toMap() {
    return {
      'test': test
  }
}

===

在 ApiProvider 类中

void addUser(User user) async {   
    Map<String, dynamic> userData = user.ToMap();
    await Firestore.instance
    .collection('user')
    .add(userData)
    .then((document) => userId = document.documentID);
  }

【问题讨论】:

  • 编写一个循环在所需的子集合中创建N个不同的文档,数组中的每个元素一个文档。

标签: flutter google-cloud-firestore


【解决方案1】:

这是最好的方法吗?

void addUser(User user) async {   
    Map<String, dynamic> userData = user.ToMap();
    await Firestore.instance.collection('user').add(userData).then(
      (document) {
        userId = document.documentID;
        for (var i = 0; i < user.address.length; i++) {
          Firestore.instance
              .collection('user')
              .document('$userId')
              .collection('address')
              .add(user.address.get(i));
            }
          },
        );
}

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 2013-07-05
    • 2023-03-18
    • 2020-10-13
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多