Convert a Stream to a Future in Flutter

Viewed 2032

a Flutter beginner here so if my question is stupid don't mind it...

How can I convert a Stream to a Future?

I have a Stream that just calls the requested URL multiple times because it's a Stream. I want to be able to get the data and not the loading state... Because I always just get loading forever

Is there something like Future.fromStream() function somewhere and I'm missing it?

Can I achieve this?

I didn't provide any code because I think it's not needed if you need the code, I can edit the question

2 Answers

Stream has firstWhere method, this will return Future

_profileService.profileStream.firstWhere((element) => false);

Stream and Future are two different concepts.

As you are using, stream is keeping the data updated, and Future is just one time. Example of using stream: Shopping Cart, listing of items Example of using future: getUserDetails after login.

If you're using stream, then you can use streambuilder to build your UI

StreamBuilder<User>(
  stream: userBloc.author, // your stream here
  builder:
      (BuildContext context, AsyncSnapshot<User> snapshot) {
    if (snapshot.connectionState == ConnectionState.active && snapshot.hasData) {
      // do your work here
    } else {
      return CircularprogressIndicator();
    }
  },
)
Related