4

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

Hussein Al-Mosawi
  • 1,464
  • 3
  • 17
  • 37

2 Answers2

6

Stream has firstWhere method, this will return Future

_profileService.profileStream.firstWhere((element) => false);
ikerfah
  • 2,612
  • 1
  • 11
  • 18
  • Note, with this approach, the returned future is always completed with an error (`Bad state: No element`). If you `await` the future, it will, of course, throw an exception. – Chuck Batson Jan 04 '23 at 23:32
-1

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();
    }
  },
)
xion
  • 1,209
  • 11
  • 17