如何在 dart 或 flutter 中获取对象列表流 "Stream<List<MyModel>>"?

How to get a Stream of lists of objects "Stream<List<MyModel>>" in dart or flutter?

我想得到一个 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.

我认为这是由于空安全,但我不确定如何处理这种情况。

对于这个例子我的练习 class:

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,
    };
  }
}


您在 map 中缺少 return 语句:

return document.docs.map((e) {
  return Exercise.fromJson(e.data() as Map<String, dynamic>);
}).toList();