首页 > 解决方案 > 如何从颤振中的for循环返回流列表

问题描述

代码和注释比我能清楚地解释它更好。基本上我想返回一些东西的流,但只基于某些参数。这些参数来自一个数组。

这是一个例子。

假设我们有一个值为 ["1", "2", "3"] 的数组

在数据库中我有一个 ["1", "2","3","4"]

我想要一个可以返回除这四个之外的所有内容的流,或者更好地表达它。我想要一个流列表,它只返回具有数组 docid 的项目,这些项目的值指定为 [1,2,3]

我在下面所做的是遍历示例数组,因此第一项“c”将是“1”。

它将采用这个“1”并使用 where 来查看 docid 是否与这个“1”匹配。我需要以某种方式存储它,然后在它“完全”填充后返回它。或根本没有填充,因为它是一个流。[1,2,3] 的示例数组将来可能会更改为 [1,2,3,4] 所以当这种情况发生时,我希望从数据库中提取数据。

     class UserData {
  String uid;
  String firstName;
  int rating;
  List<String> classes;  //need to be able to access this

  UserData.fromMap(Map<String, dynamic> data) {
    firstName = data['firstname'] ?? "";
    rating = data['rating'] ?? "";
    classes = data['classes'].cast<String>() ?? "";
  }

  

  Stream<List<ClassData>> getTheUserClasses = (() async* {
    List<ClassData> d = List<ClassData>();

    for (String c in classes) { //no longer able to access classes
      // this will store the data of the matched value
      var _matchData = Firestore.instance
          .collection("Classes")
          .where('classid', isEqualTo: c)
          .snapshots()
          .map((event) => event.documents
              .map((e) => ClassData.fromUserMap(e.data, e.documentID)));

      // and when you have it, append
      d.add(_matchData); //error here from type differences
    }

    // after the loop you can test your response then yield
    d.forEach((item) => print(item));

    // return the data which is required
    yield d;
  })();

  UserData({this.firstName, this.rating, this.classes});
}

在此处输入图像描述

这是我已经做到的一种方法。问题是更新数据时它不会刷新小部件树。

Future<void> getTheUserClasses() async {
    List<ClassData> _classList = List<ClassData>();

    for (String c in user.classes) {
      DocumentSnapshot classsnapshot =
          await Firestore.instance.collection("Classes").document(c).get();

      final data =
          ClassData.fromUserMap(classsnapshot.data, classsnapshot.documentID);

      if (data != null) {
        _classList.add(data);
      }
    }

    notifyListeners();

    classes = _classList;
  }

标签: firebaseflutterdartfirebase-realtime-databasegoogle-cloud-firestore

解决方案


推荐阅读