Flutter - 如何让 SnackBar 不向上推动 FloatingActionButton?

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

如何让SnackbarFloatingActionButton重叠,弹出时不向上推?我附上了我的简化代码以供参考。提前谢谢你。

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)
  ));
}

您可以将 SnackBarbehavior 属性 设置为 SnackBarBehavior.floating,这将在其他小部件上方显示 Snackbar

应该这样做 -

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
  ));
}

有关详细信息,请参阅 this link。

只需使用多个 Scaffold。用外层包裹内层。使用 inner 来放置所有属于它的东西,bodyappBarbottomNavigationBarfloatingActionButton 等等。从外部 bodyBuildContext 调用 showSnackBar。如果有的话,将 drawer 从内向外移动,使其保持在 SnackBar.

上方

如果您更喜欢弹出 SnackBar 像经典吐司一样,请参阅 Siddharth Patankar 的回答。也谢谢你。

下面是我回答的简化代码。

  @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),
            )),
          ),
        );
      }
    )
  );