You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter 3.10中BottomSheet被键盘遮挡,原padding方案失效求助

解决Flutter 3.10中BottomSheet被键盘覆盖的问题

Flutter 3.10版本对MediaQuery的viewInsets传递机制及showModalBottomSheet布局逻辑做了调整,导致原通过MediaQuery.of(context).viewInsets.bottom设置padding的方式失效。以下是几种可行的修复方案:

方案一:使用AnimatedPadding动态响应viewInsets变化

AnimatedPadding能自动监听MediaQuery的变化并更新内边距,确保键盘弹出时BottomSheet能及时调整:

void onTotalsButtonPressed() {
  showModalBottomSheet(
    context: context,
    builder: (context) => AnimatedPadding(
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      duration: const Duration(milliseconds: 100),
      child: SingleChildScrollView(
        child: AddProduct(
          items: Provider.of<Products>(context, listen: false).searchItems,
          type: OrderTypes.sales,
        ),
      ),
    ),
    isScrollControlled: true,
  );
}

方案二:使用Builder获取正确的上下文

如果原builder的上下文未能正确获取最新的MediaQuery值,可通过Builder包裹一层获取内部上下文:

void onTotalsButtonPressed() {
  showModalBottomSheet(
    context: context,
    builder: (context) => Builder(
      builder: (innerContext) => SingleChildScrollView(
        padding: EdgeInsets.only(bottom: MediaQuery.of(innerContext).viewInsets.bottom),
        child: AddProduct(
          items: Provider.of<Products>(context, listen: false).searchItems,
          type: OrderTypes.sales,
        ),
      ),
    ),
    isScrollControlled: true,
  );
}

方案三:通过StatefulBuilder强制更新状态

若初始渲染时viewInsets未及时更新,可借助StatefulBuilder结合addPostFrameCallback触发状态更新:

void onTotalsButtonPressed() {
  showModalBottomSheet(
    context: context,
    builder: (context) => StatefulBuilder(
      builder: (innerContext, setState) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          setState(() {});
        });
        return SingleChildScrollView(
          padding: EdgeInsets.only(bottom: MediaQuery.of(innerContext).viewInsets.bottom),
          child: AddProduct(
            items: Provider.of<Products>(context, listen: false).searchItems,
            type: OrderTypes.sales,
          ),
        );
      },
    ),
    isScrollControlled: true,
  );
}

推荐优先使用方案一,AnimatedPadding的实现更简洁且能稳定响应键盘状态变化。

内容的提问来源于stack exchange,提问作者metalmlover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:50:24