Flutter show SnackBar and return empty Container in StreamBuilder throws an Error
1,526
That's because you shouldn't display a Snackbar
while your Widget
is the process of rebuilding, a workaround that you can use is :
_displaySnackBar(BuildContext context) async {
await Future.delayed(Duration(milliseconds: 400));
scaffoldKey.currentState.showSnackBar(SnackBar(
content: Container(
height: 100,
),
));
}
and
if (snap.hasError) {
_displaySnackBar(context);
return Center(child: Text(snap.error));
}
Author by
Tornike Kurdadze
Updated on December 08, 2022Comments
-
Tornike Kurdadze over 1 year
Hello I am trying to show Snackbar if network response return error right now My Build function looks like this:
@override Widget build(BuildContext context) { NewsBloc bloc = NewsBloc(); return Scaffold( key: scaffoldKey, body: Container( color: Colors.white, child: StreamBuilder<List<BaseModel>>( stream: bloc.newsStream, builder: (BuildContext context, AsyncSnapshot<List<BaseModel>> snap) { if (snap.hasError) { scaffoldKey.currentState.showSnackBar(SnackBar( content: Container( height: 100, ), )); return Center(child: Text(snap.error)); } else if (!snap.hasData) { return Center(child: CircularProgressIndicator()); } else { return _newsList(snap.data); } }, ), ), ); }
It shows the Snackbar but also throws an error:
This Scaffold widget cannot be marked as needing to build because the framework is already in the procces
-
Khurshid Ansari over 5 years
-
-
Tornike Kurdadze over 5 yearsOoh sorry I posted a wrong code, conditional to check doesn't work as well
-
Tornike Kurdadze over 5 yearsnow it works but what if building process take mot than 400 mls?
-
diegoveloper over 5 yearsthat's is not about the process time , that time is after you receive the data from your stream , I added an extra delay after your widget is refreshed.
-
diegoveloper over 5 yearsalso you can check this answer :) stackoverflow.com/questions/52849373/…