How can I use FutureBuilder after getting userId?

2019-08-17 15:41发布

If you want to get a list of users, just set Firestore.instance.collection("users").snapshots() to the Futurebuilder's future:

But, how can I use userDataRef() to get user's data based on userId using FutureBuilder?

  Future<Stream<DocumentSnapshot>> userDataRef() async {
    final FirebaseUser user = await auth.currentUser();

    return Firestore.instance
        .collection("users")
        .document(user.uid).snapshots();
  }

This is my FutureBuilder. trying to display users favorite foods.

  FutureBuilder(
    future: Database.shared.userDataRef(),
    builder: (BuildContext context, snapshot) {
      if (!snapshot.hasData) {
        return Text("Error");
      }
      final doc = snapshot.data.documents;
      final List favoriteFoods = doc["favorite_foods"];


      return Text(favoriteFoods.toString());
    },

Any advice will be appreciated.

Thanks.

1条回答
孤傲高冷的网名
2楼-- · 2019-08-17 16:06

You can use nested FutureBuilder's like this :

  Widget nestedFutureBuilders(){
    return FutureBuilder(
      future: YourFirstRequest,
      builder: (BuildContext context, AsyncSnapshot<String> snapshotOne) {
        switch (snapshotOne.connectionState) {
          case ConnectionState.none:
            return Text('Press button to start.');
          case ConnectionState.active:
          case ConnectionState.waiting:
            return Text('Awaiting result...');
          case ConnectionState.done:
            if (snapshotOne.hasError)
              return Text('Error: ${snapshotOne.error}');
            return FutureBuilder<String>(
              future: YourSecondRequest, // which is related the first request data (snapshotOne.data).
              builder: (BuildContext context, AsyncSnapshot<String> snapshotTwo) {
                switch (snapshotTwo.connectionState) {
                  case ConnectionState.none:
                    return Text('Press button to start.');
                  case ConnectionState.active:
                  case ConnectionState.waiting:
                    return Text('Awaiting result...');
                  case ConnectionState.done:
                    if (snapshotTwo.hasError)
                      return Text('Error: ${snapshotTwo.error}');
                    return BuildYourUIHere();// you have both data here(snapshotOne.data & snapshotTwo.data)
                }
                return null; // unreachable
              },
            );
        }
        return null; // unreachable
      },
    );
  }
查看更多
登录 后发表回答