izik461
izik461

Reputation: 1173

Flutter FutureBuilder with Firestore

I'm trying to create a list in flutter, loading data asynchronously from firestore for each cell:

Future getUserDetails(String userID) async {
    DatabaseService databaseService =
        DatabaseService(currentUserId: _currentUserID);
    return databaseService.getUserDetails(userID: userID);
  }

Future sampleText() async {
    return Future.delayed(Duration(seconds: 3)).then((value) => randomString(5));
}

FutureBuilder _userAsyncCell(ClassAttendee attendeeData) {
    return FutureBuilder(
        future: getUserDetails(attendeeData.userId),//sampleText(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting)
            return Center(child: CircularProgressIndicator());
          else if (snapshot.hasData)
            return Text("DATA: ${snapshot.data}");
          else if (snapshot.hasError)
            return Text("ERROR: ${snapshot.error}");
          else
            return Text('None');
        });
  }

AND in the DatabaseService:

final CollectionReference _usersCollection =
      Firestore.instance.collection('users');

Future<User> getUserDetails({String userID}) async {
    print('Fetching User public data ${userID}');
    _usersCollection.document(userID).get().then((userJSON) {
      User user = User.fromJson(userJSON.data);
      print("Received user info: ${user.identifier}");
      return user;
    });
  }

The issue is that the data received in the futureBuilder is always nil.

When using the sampleText() instead of getUserDetails(), it's working properly.

Do you have any ideas why is this happening?

EDIT: In logs I can see, that the userDetails is properly returning the value and the futureBuilder's builder is called:enter image description here

flutter: Fetching User public data Rh8snwoI27V6pA3wkmQwBPitgl63
flutter: Received user info: Rh8snwoI27V6pA3wkmQwBPitgl63

Upvotes: 0

Views: 465

Answers (1)

Aadiyaara
Aadiyaara

Reputation: 91

Try Refactoring your code as follows.

You are not awaiting the response and hence the future returns with nil value

Future<User> getUserDetails({String userID}) async {
    print('Fetching User public data ${userID}');
    await _usersCollection.document(userID).get().then((userJSON) {
      User user = User.fromJson(userJSON.data);
      print("Received user info: ${user.identifier}");
      return user;
    });
}

Upvotes: 3

Related Questions