gpt4 book ai didi

firebase - 将 Flutter 对象与列表映射到 Firebase 实时数据库

转载 作者:行者123 更新时间:2023-12-02 02:29:38 28 4
gpt4 key购买 nike

我正在尝试将我的轮询对象保存到 Firebase 实时数据库,但我真的不知道如何使用我的轮询对象执行此操作,因为它有一个列表。我试图找到一个教程,如何将带有 map 的对象映射到 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};
}
}

这里我尝试写入数据库:

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

有人可以帮助我吗?提前致谢!

最佳答案

我已经根据您的代码创建了一个 JSON

{
"id":"",
"name":"",
"description":"",
"questions": [
{
"id":"",
"question":"",
"customAnswer":""
}
]
}

然后生成 dart 类 Use this website 。你的对象类将如下所示。

class Welcome {
Welcome({
this.id,
this.name,
this.description,
this.questions,
});

String id;
String name;
String description;
List<Question> questions;

factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
id: json["id"],
name: json["name"],
description: json["description"],
questions: List<Question>.from(json["questions"].map((x) => Question.fromJson(x))),
);

Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"description": description,
"questions": List<dynamic>.from(questions.map((x) => x.toJson())),
};

}

class Question {
Question({
this.id,
this.question,
this.customAnswer,
});

String id;
String question;
String customAnswer;

factory Question.fromJson(Map<String, dynamic> json) => Question(
id: json["id"],
question: json["question"],
customAnswer: json["customAnswer"],
);

Map<String, dynamic> toJson() => {
"id": id,
"question": question,
"customAnswer": customAnswer,
};

}

现在您将能够调用 await ...set(poll1.toJson()); 而不会出现任何错误

关于firebase - 将 Flutter 对象与列表映射到 Firebase 实时数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65251231/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com