Home > Enterprise >  How to get a Stream of lists of objects "Stream<List<MyModel>>" in dart or flu
How to get a Stream of lists of objects "Stream<List<MyModel>>" in dart or flu

Time:09-21

I want to get a Stream<List<MyModel>> and use it in a StreamBuilder later on.

But I have a problem getting the stream from firebase.

Here is my function to get the stream:

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

Error message: The return type 'List<Null>' isn't a 'List<Exercise>', as required by the closure's context.

I think this is due to null safety but I am not sure how to handle this case.

For this example my Exercise 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,
    };
  }
}


CodePudding user response:

You're missing a return statement in map:

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