Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show a Progress Indicator when loading data in StreamBuilder?

Tags:

flutter

dart

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);
like image 667
stuckedoverflow Avatar asked Jan 26 '23 12:01

stuckedoverflow


2 Answers

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
like image 83
creativecreatorormaybenot Avatar answered May 10 '23 06:05

creativecreatorormaybenot


snapshot.connectionState can tell if your data is still loading...

if (snapshot.connectionState == ConnectionState.waiting) {
  return CircularProgressIndicator();
}
like image 20
dukesy Avatar answered May 10 '23 06:05

dukesy