当你在flutter中遇到输入框响应但输入框没有显示在键盘上时
全栈老韩
全栈工程师,擅长iOS App开发、前端(vue、react、nuxt、小程序&Taro)开发、Flutter、React Native、后端(midwayjs、golang、express、koa)开发、docker容器、seo优化等。
先给出一段示例代码,键盘输入框写在modal弹窗中的情况,一些代码做了简化处理,所以不能直接运行,目的是让大家只看重要的部分,知道基本的布局。其中还使用了一些自己封装的类,所以不要直接运行。
dart
void _showCommentActionSheet(BuildContext currentContext, HomeListModel cardModel) {
showCupertinoModalPopup(
barrierColor: Colors.black.withOpacity(0.8),
context: currentContext,
builder: (BuildContext context) {
return SafelyClickWidget(
onTap: () {
KeyboardUtils.closeKeyboard(context);
},
child: TextField(
autofocus: false,
style: TextStyles.mediumText(16, Colors.white),
focusNode: viewModel.focusNode,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(horizontal: 0),
hintText: "Add a comment",
hintStyle: TextStyles.mediumText(16, Colours.FF8C8C8C),
border: InputBorder.none,
filled: true,
fillColor: Colors.transparent,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(0),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(0),
),
),
textInputAction: TextInputAction.send,
onSubmitted: (value) async {
},
onChanged: (value) {
},
),
);
},
);
}
类似这种布局,当在一个页面widget展示时,如果出现了键盘遮挡了输入框的情况,那么可以将输入框以及你想布局在安全区SafeArea中的组件可以显示在键盘之上,你可以加一个AnimatedPadding或者AnimatedContainer组件包裹他们。
当设置了对应的padding时,这2个组件可以动态的调整自组件的位置,以此可以满足不被输入框遮挡的问题。
示例如下:
dart
void _showCommentActionSheet(BuildContext currentContext, HomeListModel cardModel) {
showCupertinoModalPopup(
barrierColor: Colors.black.withOpacity(0.8),
context: currentContext,
builder: (BuildContext context) {
return SafelyClickWidget(
onTap: () {
KeyboardUtils.closeKeyboard(context);
},
child: AnimatedPadding(
padding: MediaQuery.of(context).viewInsets, // 划重点
duration: const Duration(milliseconds: 100),
child: TextField(
autofocus: false,
style: TextStyles.mediumText(16, Colors.white),
focusNode: viewModel.focusNode,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(horizontal: 0),
hintText: "Add a comment",
hintStyle: TextStyles.mediumText(16, Colours.FF8C8C8C),
border: InputBorder.none,
filled: true,
fillColor: Colors.transparent,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(0),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(0),
),
),
textInputAction: TextInputAction.send,
onSubmitted: (value) async {
},
onChanged: (value) {
},
),
),
);
},
);
}
如上述代码所示,当使用组件AnimatedPadding,并且设置padding为MediaQuery.of(context).viewInsets时,组件中包裹的子组件就可以限制在键盘的上方,因为viewInsets就是在键盘出现时,viewInsets.bottom就会响应,而且就是键盘的顶部位置。
加上设置了duration动画时间,就可以实现一个动态丝滑的向上移动动画,也不会被键盘遮挡。
本文到此结束。
发布于2024-11-09 10:31:31
浏览量208·
暂无评论,快来发表第一条评论吧