【发布时间】:2021-11-13 11:36:37
【问题描述】:
我想获得一个Stream<List<MyModel>> 并稍后在 StreamBuilder 中使用它。
但我在从 firebase 获取流时遇到问题。
这是我获取流的函数:
static Stream<List<Exercise>> getExercisesWithUpdates() {
Stream<QuerySnapshot<Object?>> querySnapshot = _firestore.collection('exercise').snapshots(); //hier kein null
Stream<List<Exercise>> test = querySnapshot.map((document) {
return document.docs.map((e) {
Exercise.fromJson(e.data() as Map<String, dynamic>);
}).toList();
});
return test;
}
错误信息:The return type 'List<Null>' isn't a 'List<Exercise>', as required by the closure's context.
我认为这是由于 null 安全性,但我不确定如何处理这种情况。
对于这个例子,我的练习课:
class Exercise {
String? id;
String? name;
String? imageName;
String? imageUrl;
String? description;
Exercise({required this.id, required this.name, this.imageName, this.imageUrl, this.description});
Exercise.empty();
Exercise.fromJson(Map<String, dynamic> json)
: this(
id: json['id']! as String,
name: json['name']! as String,
imageName: json['imageName']! as String,
imageUrl: json['imageUrl']! as String,
description: json['description']! as String);
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'imageName': imageName,
'imageUrl': imageUrl,
'description': description,
};
}
}
【问题讨论】:
标签: firebase flutter dart google-cloud-firestore dart-null-safety