【问题标题】:How to get a Stream of lists of objects "Stream<List<MyModel>>" in dart or flutter?如何在飞镖或颤振中获取对象列表“Stream<List<MyModel>>”的流?
【发布时间】:2021-11-13 11:36:37
【问题描述】:

我想获得一个Stream&lt;List&lt;MyModel&gt;&gt; 并稍后在 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&lt;Null&gt;' isn't a 'List&lt;Exercise&gt;', 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


    【解决方案1】:

    您在map 中缺少返回语句:

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

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 2021-11-23
      • 2020-08-12
      • 2021-01-24
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多