【发布时间】:2021-03-22 20:41:26
【问题描述】:
我正在尝试将我的轮询对象保存到 Firebase 实时数据库,但我真的不知道如何使用我的轮询对象执行此操作,因为它有一个列表。我试图找到一个教程如何将带有地图的对象映射到 Firebase,但没有找到。
class Poll {
String id;
String name;
String description;
List<Question> questions;
Poll({this.name, this.description, this.questions});
Poll.fromSnapshot(DataSnapshot snapshot) {
id = snapshot.key;
name = snapshot.value['name'];
description = snapshot.value['description'];
questions = snapshot.value['questions'];
}
toJson() {
return {'name': name, 'description': description, 'questions': questions};
}
}
class Question {
String id;
String question;
String customAnswer;
Question.customAnswer({this.question, this.customAnswer});
Question.fromSnapshot(DataSnapshot snapshot) {
id = snapshot.key;
question = snapshot.value['question'];
customAnswer = snapshot.value['customAnswer'];
}
toJson() {
return {'question': question, 'customAnswer': customAnswer};
}
}
这里我尝试写入 DB:
RaisedButton(
onPressed: () async {
Poll poll1 =
Poll(name: 'poll1', description: 'desc1', questions: [
Question.customAnswer(
question: 'who am i', customAnswer: 'Ostap'),
Question.customAnswer(
question: 'who are you', customAnswer: 'test'),
]);
await databaseReference
.child('Polls')
.push()
.set(poll1.toJson());
},
child: Text('Write To DB'),
这是我得到的错误:
Exception has occurred.
ArgumentError (Invalid argument: Instance of 'Question')
由await databaseReference引起
有人可以帮助我吗?提前致谢!
【问题讨论】:
-
简单保存对象会保存它。但要确保每个字段成员都有 getter 和 setter。
-
这真的有用吗?类轮询{字符串ID;字符串名称;字符串描述;列出
问题;投票({this.name,this.description,this.questions}); Poll.fromSnapshot(DataSnapshot 快照) { id = snapshot.key;名称 = 快照.值 ['名称'];描述 = 快照.值 ['描述']; questions = snapshot.value['questions']; } toJson() { return {'name': name, 'description': description, 'questions': questions}; } } -
是的,应该。否则发布相关错误,以便我们为您提供帮助。
-
谢谢,我试试看
-
我收到一个错误,它说 databaseReference 也不是问题类型,这是我的 Qestion 类问题 { String id;字符串问题;字符串自定义答案; Question.customAnswer({this.question, this.customAnswer}); Question.fromSnapshot(DataSnapshot 快照) { id = snapshot.key;问题=快照。值['问题']; customAnswer = snapshot.value['customAnswer']; } toJson() { return {'question': question, 'customAnswer': customAnswer}; } }
标签: firebase flutter dart firebase-realtime-database