Flutter中双击返回退出的SnackBar显示于导航栏上方的问题
问题根源在于:设置extendBody: true后,Scaffold的body会延伸至底部导航栏下方,而你使用的SnackBarBehavior.floating类型SnackBar不会自动避开底部导航栏,再加上margin的bottom值设为0,就导致SnackBar显示在导航栏上方。
解决步骤
- 引入Flutter内置的底部导航栏高度常量(或自定义导航栏高度)
- 调整SnackBar的
margin底部值,加上导航栏高度和额外间距
修改后的代码
首先在文件顶部导入必要包:
import 'package:flutter/material.dart';
然后修改WillPopScope内的showSnackBar代码:
WillPopScope( onWillPop: () async { DateTime now = DateTime.now(); if (currentBackPressTime == null || now.difference(currentBackPressTime!) > const Duration(seconds: 2)) { currentBackPressTime = now; // 获取默认底部导航栏高度 final double navBarHeight = kBottomNavigationBarHeight; ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: red, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), elevation: 6.0, behavior: SnackBarBehavior.floating, duration: const Duration(milliseconds: 1500), // 调整margin的bottom值,加上导航栏高度和16的间距 margin: EdgeInsets.fromLTRB(40, 0, 40, navBarHeight + 16), content: Padding( padding: const EdgeInsets.all(4.0), child: Text( 'Press back button again to exit', textAlign: TextAlign.center, style: buttonstyle, ), ), ), ); return false; } return true; }, child: child);
补充说明
kBottomNavigationBarHeight是Flutter提供的默认底部导航栏高度(值为56.0),如果你的导航栏是自定义高度,直接替换成对应的数值即可。- 额外添加的
16是间距值,可根据视觉需求调整,让SnackBar和导航栏之间保持合适距离。 - 如果不需要
extendBody: true,也可以直接移除该属性,此时floating类型的SnackBar会自动避开底部导航栏,但这会影响body的布局延伸效果。
内容的提问来源于stack exchange,提问作者ckot234
相关产品推荐
相关产品推荐

