Consider I have this
StreamBuilder(
stream: myBloc.productList,
builder: (context, AsyncSnapshot<List<Product>> snapshot) {
if (snapshot.hasData && snapshot != null) {
if (snapshot.data.length > 0) {
return buildProductList(snapshot);
}
else if (snapshot.data.length==0){
return Center(child: Text('No Data'));
}
} else if (snapshot.hasError) {
return ErrorScreen(errMessage: snapshot.error.toString());
}
return CircularProgressIndicator();
},
),
At first progress indicator will work fine but when data is not found and once 'No Data' gets displayed then the progress indicator never appears again.
How to show progress indicator while loading data only. And show no data when no data and show data when there is data?
This is how the bloc part
final _fetcher = BehaviorSubject<List<Product>>();
Observable<List<Product>> get productList => _fetcher.stream;
Just fetch data from RESTAPI then put it in the List
List<Product> product = await _repository.fetchProduct().catchError((err) => _fetcher.addError(err));
_fetcher.sink.add(product);
First of all, snapshot.hasData
and snapshot.data != null
are literally the exact same (hasData
calls data != null
internally). I actually misread your code there, but snapshot
will never be null
. Thus you can drop it anyway.
The problem here is that you have a misunderstanding of how Stream
's work. The stream will not push an update if you are currently adding a product
. How would it know when to do that anyway? It will only update if you call add
on it and in that case the data
will not be null
. Hence, there is no progress indicator.
You can easily fix that by adding null
when loading:
_fetcher.sink.add(null); // to show progress indicator
List<Product> product = await _repository.fetchProduct().catchError((err) => _fetcher.addError(err));
_fetcher.sink.add(product); // to show data
snapshot.connectionState
can tell if your data is still loading...
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With