【问题标题】:Adding an Object to Cloud Firestore using Flutter使用 Flutter 向 Cloud Firestore 添加对象
【发布时间】:2018-12-12 16:42:08
【问题描述】:

我想在我的 Flutter 应用中向 Google Cloud Firestore 添加一个对象,如下所示:

我已经做了一个回复类:

class Reply {
Reply(this.replyName, this.replyText, this.replyVotes);
  final String replyName;
  final String replyText;
  final String replyVotes;

  String getName() {
    return replyName;
  }

  String getText() {
    return replyText;
  }

  String getVotes() {
    return replyVotes;
  }
}

如何将回复对象添加到云 Firestore?

编辑: 澄清一下,我想创建一个数据类型为 Object 的字段,其中包含字段:Reply Object Image

【问题讨论】:

  • 您是否尝试过添加Map
  • 如何使用地图在 Firestore 文档中创建新对象?我可以使用地图在文档中添加值,但不能创建具有这些值的对象。

标签: firebase dart google-cloud-firestore flutter


【解决方案1】:

首先,我强烈建议您使用一个文件来定义您的所有模式和/或模型,这样您的数据库结构就有一个单一的参考点。像一些名为 dbSchema.dart 的文件:

import 'package:meta/meta.dart';

class Replies {

  final String title;  
  final Map coordinates;

  Replies({
    @required this.title,
    @required this.coordinates,
  });

 Map<String, dynamic> toJson() =>
  {
    'title': title,
    'coordinates': coordinates,
  };

}

并将您希望成为对象类型 Map 的字段。然后,在您要插入数据库的页面上,导入 dbSchema.dart 并创建一个新模型:

Replies _replyObj = new Replies(
  title: _topic,
  coordinates: _coordinates,
);

假设您在此之前已经定义了本地 _coordinates(或其他)对象,例如:

_coordinates = {
 'lat': '40.0000',
 'lng': '110.000', 
};

然后插入 Firestore,添加对象的 toJson 方法(不能插入/更新普通的 Dart 模型):

CollectionReference dbReplies = Firestore.instance.collection('replies');

Firestore.instance.runTransaction((Transaction tx) async {
  var _result = await dbReplies.add(_replyObj.toJson());
  ....

更新 (5/31)

要将读取的文档转换回对象,您需要在类中添加fromJson,如下所示:

Replies.fromJson(Map parsedJson) {
    id = parsedJson['id']; // the doc ID, helpful to have
    title = parsedJson['title'] ?? '';
    coordinates = parsedJson['coordinates'] ?? {};
}

所以当你查询数据库时:

QuerySnapshot _repliesQuery = await someCollection
        .where('title', isEqualTo: _title)
        .getDocuments();

List<DocumentSnapshot> _replyDocs = _repliesQuery.documents;

您可以从每个快照中创建一个对象:

for (int _i = 0; _i < _replyDocs.length; _i++) {

  Replies _reply = Replies.fromJson(_replyDocs[_i].data);
  _reply.id = _replyDocs[_i].documentID;

  // do something with the new _reply object
}

【讨论】:

  • 不错的答案。添加一些有关将 Firestore 读取文档转换回 Dart 模型的详细信息可能会有所帮助。
  • 很好的答案,有用且直接。 +1 @KrishnaShetty 反馈。对于反向过程有额外的帮助会很棒。有人会这么好心帮忙吗?
  • 更新为包含从文档读回对象的映射。
  • 即在 Replies 对象中有 2 个属性的情况。如果你有更多呢?
【解决方案2】:

您可以像这样运行Firestore 事务:

    Firestore.instance.runTransaction((transaction) async {
          await transaction.set(Firestore.instance.collection("your_collection").document(), {
            'replyName': replyName,
            'replyText': replyText,
            'replyVotes': replyVotes,
          });
        });

【讨论】:

  • 使用此方法,我可以向文档添加值。相反,我想做的是在存储这些值的 Firestore 文档中创建一个对象。
  • 你不能不在另一个文档中创建一个文档(对象),首先你应该创建一个集合。集合 > 文档 > 集合 > 文档 ...
  • 如何访问 Flutter 中的子集合?
【解决方案3】:

空安全码:

说这是你的对象。

class MyObject {
  final String foo;
  final int bar;

  MyObject._({required this.foo, required this.bar});

  factory MyObject.fromJson(Map<String, dynamic> data) {
    return MyObject._(
      foo: data['foo'] as String,
      bar: data['bar'] as int,
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'foo': foo,
      'bar': bar,
    };
  }
}

要将此对象添加到 Cloud Firestore,请执行以下操作:

MyObject myObject = MyObject.fromJson({'foo' : 'hi', bar: 0}); // Instance of MyObject.

var collection = FirebaseFirestore.instance.collection('collection');
collection
    .add(myObject.toMap()) // <-- Convert myObject to Map<String, dynamic>
    .then((_) => print('Added'))
    .catchError((error) => print('Add failed: $error'));

【讨论】:

    【解决方案4】:

    @Laksh22 据我了解,您的意思是这样的:

    Firestore.instance.runTransaction((transaction) async {
        await transaction.set(Firestore.instance.collection("your_collection").document(), {
            'reply' : {
            'replyName': replyName,
            'replyText': replyText,
            'replyVotes': replyVotes,
        }
    });
    

    就像上面的截图一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2018-11-21
      • 1970-01-01
      • 2019-09-13
      • 2018-04-17
      • 2020-08-06
      • 2019-02-19
      相关资源
      最近更新 更多