0

In my flutter app I'm building a scrollable list filled with data from FireBase. So far my code looks as follows:

class FollowersListState extends State<FollowersUsersList> {

  @override
  Widget build(BuildContext context) {


    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('user').where("author", isEqualTo: getUserEmail()).snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CupertinoActivityIndicator();

        return _buildList(context, snapshot.data.docs);
      },
    );
  }

In the code above there is this line:

where("author", isEqualTo: getUserEmail())

getUserEmail() is a method that takes the user's email from local shared preferences:

Future<String> getUserEmail() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString('loginEmail');
}

but - as you can see - it returns the Future<String> instead of String, so I cannot use it in my implementation in the StreamBuilder<QuerySnapshot>. What is the best way to handle it in that case?

Thanks!

randomuser1
  • 2,733
  • 6
  • 32
  • 68
  • can't you put `getUserEmail` in `initState`? – John Joe Oct 20 '20 at 16:48
  • @pskink I was not sure how exactly I could use `FutureBuilder` to build a stream, could you please give me some hint or show some quick example code as the answer to this question? thanks! – randomuser1 Oct 20 '20 at 17:00
  • @JohnJoe can you please show me some short code snippet how could I do it? I still cannot assign the returned value to a normal string there... Thanks! – randomuser1 Oct 20 '20 at 17:02

1 Answers1

1

You can't unpack a Future into a synchronous value within the build method. You will need to wrap the StreamBuilder in a FutureBuilder that gets the email ahead of time:

FutureBuilder(
  future: getUserEmail(),
  builder: (_, emailSnapshot) {
    if (!emailSnapshot.hasData) {
      return CircularProgressIndicator(); // Or something
    }
    return StreamBuilder(
      stream: Firestore.instance.collection('user').where("author", isEqualTo: emailSnapshot.data).snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CupertinoActivityIndicator();

        return _buildList(context, snapshot.data.docs);
      },
    ),
  },
),
Abion47
  • 22,211
  • 4
  • 65
  • 88