![](/img/trans.png)
[英]How to save a list of objects in Firebase Firestore with flutter
[英]Flutter | How to get a List of Objects from Firestore?
这是我的问题 Object:
class Question {
String text;
String correctAnswer;
bool answer;
Question(String q, bool a, String ca) {
text = q;
answer = a;
correctAnswer = ca;
}
}
我想从 Firestore 获取问题列表,如下所示:
List<Question> questionBank = [];
Firestore看起来像这样:
我怎样才能做到这一点?
你可以像这样从firestore获取数据
void _onPressed() {
firestoreInstance.collection("Questiions").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
print(result.data());
});
});
}
有关更多详细信息,您可以参考此https://medium.com/firebase-tips-tricks/how-to-use-cloud-firestore-in-flutter-9ea80593ca40
从 Cloud Firestore 检索问题并转换为列表:
Future<List<Question>> fetchQuestions(String userId) async {
final questions = new List<Question>();
final doc = await FirebaseFirestore.instance.collection('Questions').doc(userId).get();
final questionsTmp = doc.data().questions;
questionsTmp.forEach((questionTmp) {
questions.add(Question.fromMap(questionTmp));
});
return questions;
}
在问题 class 中添加 fromMap 方法:
class Question {
String text;
String correctAnswer;
bool answer;
Question(String q, bool a, String ca) {
text = q;
answer = a;
correctAnswer = ca;
}
static Question fromMap(Map<String, dynamic> map) {
return Question(
map['text'],
map['answer'],
map['correctAnswer'].ToString() == 'true'
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.