考虑我有这个
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();
},
),
Run Code Online (Sandbox Code Playgroud)
起初,进度指示器可以正常工作,但是当未找到数据并且显示“无数据”时,进度指示器将不再出现。
如何仅在加载数据时显示进度指示器。无数据时显示无数据,有数据时显示数据?
这就是集团部分的方式
final _fetcher = BehaviorSubject<List<Product>>();
Observable<List<Product>> get productList => _fetcher.stream;
Run Code Online (Sandbox Code Playgroud)
只需从 RESTAPI 获取数据然后将其放入列表中
List<Product> product = await _repository.fetchProduct().catchError((err) => _fetcher.addError(err));
_fetcher.sink.add(product);
Run Code Online (Sandbox Code Playgroud)
首先,snapshot.hasData和snapshot.data != null实际上是完全相同的(内部hasData调用data != null)。我实际上误读了你的代码,但snapshot永远不会null。因此你无论如何都可以放弃它。
这里的问题是你对如何Stream工作有误解。如果您当前正在添加product. 它怎么知道什么时候该这么做呢?仅当您调用add它时它才会更新,在这种情况下它data不会更新null。因此,没有进度指示器。
您可以通过null在加载时添加以下内容来轻松修复该问题:
_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
Run Code Online (Sandbox Code Playgroud)
小智 5
snapshot.connectionState可以判断您的数据是否仍在加载...
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7180 次 |
| 最近记录: |