Flutter bottomSheet 输入框 键盘遮挡解决:2种新思路

相信各位朋友做flutter开发的时候,在处理bottom sheet中输入框的时候,多少会有点不能满足需求。今天就来介绍三种思路,各有优劣,朋友们在工作中可以参考参考

网上普遍的解决方案:AnimatedPadding

这其实和 AnimatedPadding 并没有什么关系,其核心知识点还是利用了 MediaQuery.of(context).viewInsets.bottom 关于 viewInsets 这个属性,源码中的注释是这样说的

The parts of the display that are completely obscured by system UI, typically by the device’s keyboard. 意思就是被系统用户界面完全遮挡的部分,而这系统界面,一般也就是键盘。

因此,相信通过这,我们就明白了以下两点:

  1. 我们可以通过 MediaQuery.of(context).viewInsets.bottom 来获取键盘的高度
  2. 我们也可以通过它,来控制我们输入框显示的位置

使用 AnimatedPadding 的源码如下

Future<T?> showSheet<T>(
  BuildContext context,
  Widget body, {
  bool scrollControlled = false,
}) {
  return showModalBottomSheet(
      context: context,
      elevation: 0,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.25),
      isScrollControlled: scrollControlled,
      builder: (ctx) {
        return AnimatedPadding(
          padding: EdgeInsets.only(
            // 下面这一行是重点
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          duration: Duration.zero,
          child: Container(
            padding: const EdgeInsets.all(20),
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.only(topLeft: Radius.circular(16), topRight: Radius.circular(16)),
              color: Colors.white,
            ),
            child: body,
          ),
        );
      });
}

// 弹窗内容
Widget _buildWidthColumn() {
  return Column(
    mainAxisSize: MainAxisSize.min,
    children: [
      Container(
        height: 160,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colors.lightGreen,
        ),
      ),
      const TextField(),
      Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colors.teal,
        ),
        height: 160,
        margin: const EdgeInsets.only(top: 20),
      )
    ],
  );
} 

显示弹窗:showSheet(con

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值