使用Flutter将对象添加到Cloud Firestore [英] Adding an Object to Cloud Firestore using Flutter
问题描述
我想像这样在Flutter应用程序中向Google Cloud Firestore添加对象:
I want to add an object to Google Cloud Firestore in my Flutter app like this:
我已经进行了回复:
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;
}
}
如何将Reply对象添加到Cloud Firestore?
How do I add a Reply object to cloud Firestore?
编辑:
为了澄清,我想创建一个数据类型为 Object <的字段。 / code>里面有字段:回复对象图片
推荐答案
首先,我强烈建议您使用一个定义所有模式和/或模型的文件,以便为您提供一个参考点db结构。就像某些名为dbSchema.dart的文件:
first, i highly recommend you have a single file that defines all of your schemas and/or models so there's a single point of reference for your db structure. like some file named 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,
};
}
并使要成为对象类型的字段成为对象类型地图。然后,在该页面上,您将插入db中,导入dbSchema.dart并创建一个新模型:
and make the field that you want to be an object type Map. then, on the page you're going to insert into the db, import dbSchema.dart and create a new model:
Replies _replyObj = new Replies(
title: _topic,
coordinates: _coordinates,
);
这假设您已在此之前定义了本地_coordinates(或其他)对象,例如:
this assumes you've defined your local _coordinates (or whatever) object prior to this, with something like :
_coordinates = {
'lat': '40.0000',
'lng': '110.000',
};
然后要将其插入Firestore,请添加对象的toJson方法(您不能插入/更新普通Dart模型):
and to then insert into Firestore, add the object's toJson method (you cannot insert/update a plain Dart model):
CollectionReference dbReplies = Firestore.instance.collection('replies');
Firestore.instance.runTransaction((Transaction tx) async {
var _result = await dbReplies.add(_replyObj.toJson());
....
更新(5/31)
要转换将文档读回到对象中,您需要向类中添加 fromJson
,例如:
To convert the document read back into an object you need to add a fromJson
to the class, like so:
Replies.fromJson(Map parsedJson) {
id = parsedJson['id']; // the doc ID, helpful to have
title = parsedJson['title'] ?? '';
coordinates = parsedJson['coordinates'] ?? {};
}
因此,当您查询数据库时:
so when you query the db:
QuerySnapshot _repliesQuery = await someCollection
.where('title', isEqualTo: _title)
.getDocuments();
List<DocumentSnapshot> _replyDocs = _repliesQuery.documents;
您可以从每个快照中创建一个对象:
you can create an object out of each snapshot:
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
}
这篇关于使用Flutter将对象添加到Cloud Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!