I am using StreamBuilder
like this -
StreamController streamController = StreamController.broadcast();
StreamBuilder(
stream: streamController.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
return (snapshot.hasData == true) //THIS CONDITION!!!
? CircularProgressIndicator()
: myWidget();
)
I am adding to my stream like this -
onPressed: () {
streamController.add(null);
},
I am unable to understand the condition I should check to display the progress indicator or my widget. Since I am not passing any data, I can't use hasData
. I tried passing dummy data but hasData
never becomes false (even after the async function is over).
I tried using connectionState
but that is always active. I have no idea why it is not changing to waiting
state. It does when I use FutureBuilder
. (I thought I could just check that if the state is waiting
, show the progress indicator but that doesn't work. Why??)
Please help.
Always when I have an async call that returns me Future data and also I need this response to update my UI layer using streams I think in BLoC pattern. Is needed a little bit more code but will simplify your problem and make your code more readable, scaleable, and keep streams and async calls out from UI code as other things too.
In your case It's simple:
An enum to track what is the state of the
async
call a Network API call by example.A BLoC class that expose a stream and inside this class we create method that call a Network API by example and when the results is fetched we can hold the values, transform this values, send to UI using streams and other things. Here in
downloadData
after the Future object is completed we just put into stream aDownloadState
value and this will force the widgets that are listening controller.stream be rebuilded in UI layer withStreamBuilder
help. If we got some error from network call we put this in stream error outputcontroller.sink.addError
and in UI layer we'll able to check this withsnapshot.hasError
property.In your UI layer...
and in the onPress Event
With this approach you remove of your UI layer stream objects and controllers, no setState calls is needed, you will have a specific file with your business logic and external api calls and this can make more easy this kind of job where we have Futures and Streams working together.
I Hope it helps.