一文解决Flutter中使用TextField遇到的各种疑难杂症

页面中有输入框,键盘弹起,页面溢出

可以使用 SingleChildScrollView 包裹布局
这里还需要了解一个 Scaffold 中的一个属性 resizeToAvoidBottomInset

/// If true the [body] and the scaffold’s floating widgets should size
/// themselves to avoid the onscreen keyboard whose height is defined by the
/// ambient [MediaQuery]'s [MediaQueryData.viewInsets] bottom property.
///
/// For example, if there is an onscreen keyboard displayed above the
/// scaffold, the body can be resized to avoid overlapping the keyboard, which
/// prevents widgets inside the body from being obscured by the keyboard.
///
/// Defaults to true.

官方文档给出的解释就是处理键盘遮挡问题,默认是 true,如果不希望顶起需要设置为 false。
在 sdk 低版本的时候是使用 resizeToAvoidBottomPadding 需要将其设置为 false,现在已经弃用。但网上很多文章还没有改正,仍然用的 resizeToAvoidBottomPadding。

键盘弹起的情况下,返回前先收起键盘

分两种情况
一种是使用系统的返回键,比如 android 底部导航自带的返回,
另一种是使用导航栏自定义的返回键
第一种情况需要在页面根布局使用 WillPopScope 在 onWillPop 中拦截返回处理。
原理都是通过判断输入框是否获取了焦点

      onWillPop: () {
        if (_focusNode.hasFocus) {
          FocusScope.of(context).unfocus();
        } else {
          return Future.value(true);
        }
      },
编辑页面底部有悬浮按钮,键盘弹起的时候,要顶上去,保证按钮不被键盘遮挡

当底部有固定的组件,比如提交按钮,我们在键盘弹起的时候希望按钮贴着键盘顶部固定,但是中间滚动视图可以自由滚动
可以在 SingleChildScrollView 外部再使用 Stack 包裹,悬浮按钮使用 Positioned 定位,
还要⚠️注意要给滚动组件底部留出距离防遮挡,同时还有动态加上 bottomBar 的高度,因为在 iphoneX 以上的手机,会有个虚拟按键,如果不加上该按键高度,同样会被遮挡
高度获取方法:MediaQuery.of(context).padding.bottom

dialog弹窗中有输入框,弹起键盘布局溢出

在 showDialog 布局中使用 Scaffold 包裹,不要忘了将 backgroundColor 设为透明。
如果弹窗过高,还是需要将高度固定,然后使用 SingleChildScrollView ,弹窗中同样也可以在执行关闭的时候拦截,判断键盘是否弹起,如果弹起则要先关闭键盘。

    showDialog(
        context: context,
        builder: (c) {
          return Scaffold(
            backgroundColor: Colors.transparent,
            body: Container(
                height: BaseTheme.getScreenHeight() * 0.4,
                padding: EdgeInsets.only(left: 8.w, right: 8.w),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                    ],
                  ),
                ),
            ),
          );
        });
键盘焦点完成切换,切换到最后一个后,关闭

给所有输入框绑定 FoucusNode
在 maxLines=1 的情况下,输入框不支持换行,换行按钮会变成 done
监听 onEditingComplete 方法

                onEditingComplete: () {
                  if (code.isEmpty) {
                    //如果还有其它未填写的输入框,则切换焦点过去
                    FocusScope.of(context).requestFocus(_focusNode);
                    return;
                  }
                  //收起键盘
                  FocusScope.of(context).unfocus();
                },
点击输入框以外的区域收起键盘

根布局使用 GestureDetector 或者 InkWell 包裹,点击的时候收起键盘。

监听软键盘是否弹出
  • 可以用第三方插件比如
    https://pub.dev/packages/flutter_keyboard_visibility
    大概使用用法是使用组件包裹,通过回调监听,然后根据状态自己处理
  • _focusNode.hasFocus
    这个方法在前面有提过,也是最简单的办法,局限性就是需要动作去触发检测。此方法适用于在点击返回按钮的时候
                    onTap: () {
                      if (_focusNode.hasFocus || _focusNodeNote.hasFocus) {
                        FocusScope.of(context).unfocus();
                        return;
                      }
                      Navigator.pop(context);
                    }
  • 使用 WidgetsBinding 添加监听
    首先页面要 with WidgetsBindingObserver
    然后 在 initState() 实例化监听
    WidgetsBinding.instance.addObserver(this);
    实现 didChangeMetrics() 方法
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if(MediaQuery.of(context).viewInsets.bottom==0){
        LogUtils.v("关闭键盘");
      }else{
        LogUtils.v("显示键盘");
      }
    });
  }

最后要记得销毁

   @override
  void dispose() {
    // TODO: implement dispose
    //销毁
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值