Flutter TextField键盘溢出处理

TextField的键盘溢出该怎么解决

两种方法:

方法1:使用禁止滚动resizeToAvoidBottomInset
方法2:SingleChildScrollView防止溢出组件

class MyApp1 extends StatefulWidget {
  const MyApp1({Key? key}) : super(key: key);

  @override
  State<MyApp1> createState() => _MyApp1State();
}

class _MyApp1State extends State<MyApp1> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SizedBox(
          height: 350,
        ),
        TextField(
          decoration: InputDecoration(
            hintText: "文本输入框如果溢出该如何解决?",
          ),
        )
      ],
    );
  }
}

可以看到现在的代码,我们是会溢出的,那么我们该如何解决这个问题呢?

首先展示第一种解决方案:

class MyApp1 extends StatefulWidget {
  const MyApp1({Key? key}) : super(key: key);

  @override
  State<MyApp1> createState() => _MyApp1State();
}

class _MyApp1State extends State<MyApp1> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          SizedBox(
            height: 350,
          ),
          TextField(
            decoration: InputDecoration(
              hintText: "文本输入框如果溢出该如何解决?",
            ),
          )
        ],
      ),
    );
  }
}

在外层添加SingleChildScrollView即可:

 可以看到现在第一种方法我们不会溢出了,

SingleChildScrollView是防止溢出的组件,它只能接受一个子组件。这个组件应该在没有超出太多的情况下使用,
不适合在超出很多的情况下使用,因为SingleChildScrollView不支持基于Sliver的延迟实例化模型,所以一旦超出较多的内容,那么它将会十分的昂贵(性能较差),如果超出很多的话,那么建议使用ListView

现在展示第二种方法:

class MyApp1 extends StatefulWidget {
  const MyApp1({Key? key}) : super(key: key);

  @override
  State<MyApp1> createState() => _MyApp1State();
}

class _MyApp1State extends State<MyApp1> {
  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Scaffold(
      resizeToAvoidBottomInset: false,//如果为 true,主体和脚手架的浮动小部件应自行调整大小以避免屏幕键盘的高度由环境MediaQuery的MediaQueryData.viewInsets bottom属性定义。
      body: Column(
        children: [
          SizedBox(
            height: 350,
          ),
          Container(
            color: Colors.red,
            width: size.width,
            height: 46,
            child: TextField(
              decoration: InputDecoration(
                hintText: "文本输入框如果溢出该如何解决?",
              ),
            ),
          ),
          Container(
            color: Colors.red,
            width: size.width,
            height: 46,
            child: TextField(
              decoration: InputDecoration(
                hintText: "文本输入框如果溢出该如何解决?",
              ),
            ),
          )
        ],
      ),
    );
  }
}

 这次直接写了两个,可以看到不会报错,但是可以看到,下面那个输入框被键盘遮住了,所以其实并不推荐此方法。

这次就总结了这两种方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值