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));
        }
Share:
1,526
Tornike Kurdadze
Author by

Tornike Kurdadze

Updated on December 08, 2022

Comments

  • Tornike Kurdadze
    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
    
  • Tornike Kurdadze
    Tornike Kurdadze over 5 years
    Ooh sorry I posted a wrong code, conditional to check doesn't work as well
  • Tornike Kurdadze
    Tornike Kurdadze over 5 years
    now it works but what if building process take mot than 400 mls?
  • diegoveloper
    diegoveloper over 5 years
    that'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
    diegoveloper over 5 years
    also you can check this answer :) stackoverflow.com/questions/52849373/…