2

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
  • 955
  • 2
  • 10
  • 24

3 Answers3

4

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));
        }
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
0

It's a workarround but worked for me

Future<void> _snackBar(String text, context) async {
    Scaffold.of(context).showSnackBar(Helper.snackBarInfo(text));
}
limars
  • 56
  • 3
0
StreamBuilder(
    stream: bloc.stream,
    builder: (BuildContext context,
        AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        SchedulerBinding.instance
              .addPostFrameCallback((_) {
            Scaffold.of(context).showSnackBar(
              SnackBar(
                content: Text(
                        snapshot.data.error,
                        style: TextStyle(fontSize: 16)),
                duration: Duration(seconds: 3),
              ),
            );
          }); 
      }
      return Container();
    }),
David Buck
  • 3,752
  • 35
  • 31
  • 35