How Do I convert Stream to List

后端 未结 1 2008
一生所求
一生所求 2021-01-02 08:54

I\'m querying Firestore and getting a Stream back as a Stream of QuerySnapshots. I need to map the included Documents in the stream to a List of objects.

The code be

相关标签:
1条回答
  • 2021-01-02 09:33

    First of all, think about this: this function has to return very quickly. All functions do, otherwise UI would hang. However, you are expecting the function to return something that comes from the internet. It takes time. The function has to return. There is no way for a function to simply do a network request and return you the result. Welcome to the world of asynchronous programming.

    Furthermore, the stream you have is not a stream of DocumentSnapshots (which you can convert to UserTasks), but a stream of QuerySnapshots (which you can convert to List<UserTask>s). Notice the plural there. If you simply want to get all your UserTasks once, you should have a Future instead of a Stream. If you want to repeatedly get all your UserTasks after each change, then using a Stream makes sense.

    Since you said you want to get a List<UserTask>, I'm assuming you want to get the collection of UserTasks only once.

    Here's what your code becomes in this light:

      Future<List<UserTask>> getUserTaskList() async {
    
        QuerySnapshot qShot = 
          await Firestore.instance.collection('userTasks').getDocuments();
    
        return qShot.documents.map(
          (doc) => UserTask(
                doc.data['id'],
                doc.data['Description'],
                etc...)
        ).toList();
      }
    
      main() async {
        List<UserTask> tasks = await getUserTaskList();
        useTasklist(tasks); // yay, the list is here
      }
    
    

    Now if you really wanted to use a stream, here's how you could do it:

      Stream<List<UserTask>> getUserTaskLists() async {
    
        Stream<QuerySnapshot> stream = 
          Firestore.instance.collection('userTasks').snapshots();
    
        return stream.map(
          (qShot) => qShot.documents.map(
            (doc) => UserTask(
                doc.data['id'],
                doc.data['Description'],
                etc...)
          ).toList()
        );
      }
    
      main() async {
        await for (List<UserTask> tasks in getUserTaskLists()) {
          useTasklist(tasks); // yay, the NEXT list is here
        }
      }
    
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题