Flutter show Snackbar inside build

Issue

I implemented the BLoC pattern in my app by I have a problem.

Once I have a special event, I need to show a snackbar, but I have this error :

The following assertion was thrown building InteractWithMorceauPage(dirty, dependencies: [MediaQuery], state: _InteractWithMorceauPageState#25201):
setState() or markNeedsBuild() called during build.

This Scaffold widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: Scaffold
  dependencies: [TickerMode, MediaQuery, _InheritedTheme, _LocalizationsScope-[GlobalKey#dc380], Directionality]
  state: ScaffoldState#8a46b(tickers: tracking 3 tickers)
The widget which was currently being built when the offending call was made was: InteractWithMorceauPage
  dirty
  dependencies: [MediaQuery]
  state: _InteractWithMorceauPageState#25201

Here is what I’m doing :

   else if (widget.state is TickNotPossibleState){
      buttonState = PAUSE;
      Scaffold.of(context).showSnackBar(SnackBar(content: Text("My Snackbar text!")));
    }

    return _generatePage(buttonState);

Solution

Try showsnackbar in bloc listener and make sure bloc listener define under scaffold.

Answered By – guccisekspir

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.