Flutter - How to make SnackBar to not push FloatingActionButton upward?

5,272

Solution 1

Simply use multiple Scaffolds. Wrap the inner one with an outer one. Use inner to put everything belong to it, body, appBar, bottomNavigationBar, floatingActionButton and so on. Call showSnackBar from outer's body's BuildContext. If any, move drawer from inner to outer to keep it above the SnackBar.

If you prefer to popup the SnackBar like a classic toast, see Siddharth Patankar's answer. Thank you for that too.

Below is the simplified code for my answer.

  @override
  Widget build(BuildContext context) => Scaffold(
    drawer : Drawer(child: Container()),
    body: Builder(
      builder : (BuildContext context){
        this.context = context;
        return Scaffold(
          body: Container(),
          floatingActionButton: FloatingActionButton(
            onPressed: () => Scaffold.of(context).showSnackBar(SnackBar(
              duration: Duration(milliseconds : 1000),
              content: Container(height: 30),
            )),
          ),
        );
      }
    )
  );

Solution 2

You can set the behavior property of the SnackBar to SnackBarBehavior.floating which will display the Snackbar above other widgets.

This should do it -

class Screen extends StatefulWidget{

  @override
  State<StatefulWidget> createState() => ScreenState();
}

class ScreenState extends State<Screen>{

  BuildContext context;

  @override
  Widget build(BuildContext context) => Scaffold(
    floatingActionButton: FloatingActionButton(
      onPressed: action,
    ),
    body: Builder(
      builder : (BuildContext context){
        this.context = context;
        return Container();
      }
    )
  );

  action() => Scaffold.of(context).showSnackBar(SnackBar(
    duration: Duration(milliseconds : 1000),
    content: Container(height: 10)
    behavior: SnackBarBehavior.floating, // Add this line
  ));
}

See this link for more information.

Share:
5,272
stackunderflow
Author by

stackunderflow

Updated on December 15, 2022

Comments

  • stackunderflow
    stackunderflow over 1 year

    How to make the Snackbar to overlap the FloatingActionButton and not push it up upward when popped up? I've attached my simplified code for reference. Thank you in advance.

    class Screen extends StatefulWidget{
    
      @override
      State<StatefulWidget> createState() => ScreenState();
    }
    
    class ScreenState extends State<Screen>{
    
      BuildContext context;
    
      @override
      Widget build(BuildContext context) => Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: action,
        ),
        body: Builder(
          builder : (BuildContext context){
            this.context = context;
            return Container();
          }
        )
      );
    
      action() => Scaffold.of(context).showSnackBar(SnackBar(
        duration: Duration(milliseconds : 1000),
        content: Container(height: 10)
      ));
    }