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: "文本输入框如果溢出该如何解决?",
),
),
)
],
),
);
}
}
这次直接写了两个,可以看到不会报错,但是可以看到,下面那个输入框被键盘遮住了,所以其实并不推荐此方法。
这次就总结了这两种方法