我想在我的应用程序中添加一个对象到,如下所示:
我已经上了一堂回覆课:
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对象?
编辑:,为了澄清,我想创建一个数据类型为Object
的字段,其中包含字段:应答对象图像
发布于 2018-07-08 05:00:13
首先,我强烈建议您有一个文件来定义所有模式和/或模型,以便为您的db结构提供一个参考点。就像一个名为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的字段。然后,在要插入到db的页面上,导入dbSchema.dart并创建一个新模型:
Replies _replyObj = new Replies(
title: _topic,
coordinates: _coordinates,
);
这假设您在此之前已经定义了本地_coordinates (或其他什么)对象,如下所示:
_coordinates = {
'lat': '40.0000',
'lng': '110.000',
};
然后,将对象的toJson方法添加到Firestore中(不能插入/更新普通的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
}
发布于 2021-06-06 08:14:25
空安全代码:
说这是你的目标。
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,
};
}
}
若要将此对象添加到云防火墙,请执行以下操作:
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'));
发布于 2018-07-04 13:30:56
您可以像这样运行Firestore
事务:
Firestore.instance.runTransaction((transaction) async {
await transaction.set(Firestore.instance.collection("your_collection").document(), {
'replyName': replyName,
'replyText': replyText,
'replyVotes': replyVotes,
});
});
https://stackoverflow.com/questions/51170298
复制相似问题