flutter输入框 键盘遮挡解决
时间: 2023-06-19 21:08:08 浏览: 283
在Flutter中,可以使用`ListView`或`SingleChildScrollView`等来解决键盘遮挡问题。以下是一些步骤:
1. 在`Scaffold`中使用`resizeToAvoidBottomInset`属性将页面的底部留出足够的空间,以避免键盘遮挡内容。
```dart
Scaffold(
resizeToAvoidBottomInset: true,
...
)
```
2. 在输入框的`TextField`中使用`FocusNode`和`MediaQuery`来监听焦点变化和键盘高度。
```dart
class _MyPageState extends State<MyPage> {
final FocusNode _focusNode = FocusNode();
double _keyboardHeight = 0;
@override
void initState() {
super.initState();
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
_getKeyboardHeight();
}
});
}
void _getKeyboardHeight() {
final double height = MediaQuery.of(context).viewInsets.bottom;
setState(() {
_keyboardHeight = height;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true,
body: SingleChildScrollView(
child: Column(
children: [
TextField(
focusNode: _focusNode,
...
),
SizedBox(height: _keyboardHeight),
],
),
),
);
}
}
```
3. 将`SizedBox`放置在输入框下方,其高度等于键盘高度,这样当键盘弹出时,页面会自动滚动到适当的位置。
```dart
SizedBox(height: _keyboardHeight),
```
这样,当键盘弹出时,页面会自动滚动到输入框的上方,从而避免了键盘遮挡问题。
阅读全文
相关推荐

















