将模型中的列表另存为Firestore中的集合

时间:2019-01-16 23:38:23

标签: flutter google-cloud-firestore

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

查看代码在Firestore中生成的结果。

enter image description here

===

代码:

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);
  }

1 个答案:

答案 0 :(得分:0)

这是最好的方法吗?

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));
            }
          },
        );
}