2024-01-18-Flutter使用键盘上部弹出输入框
flutter中使用键盘顶起输入框,大多数使用场景是评论等相关场景,该文章记录来自于网上大佬的技术分享,没记住是谁的。
使用一个新页面,顶部使用透明区域,底部使用输入框,然后获得焦点的时候弹起键盘:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class CommentWidget extends StatelessWidget {
final ValueChanged onEditingCompleteText;
final TextEditingController controller = TextEditingController();
CommentWidget({required this.onEditingCompleteText, super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: Column(
children: <Widget>[
Expanded(
child: GestureDetector(
child: Container(
color: Colors.transparent,
),
onTap: () {
Navigator.pop(context);
},
),
),
Container(
color: const Color(0xFFF4F4F4),
padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.w),
child: Container(
decoration: const BoxDecoration(color: Colors.white),
child: TextField(
controller: controller,
autofocus: true,
style: TextStyle(fontSize: 16.sp),
//设置键盘按钮为发送
textInputAction: TextInputAction.send,
keyboardType: TextInputType.multiline,
onEditingComplete: () {
//点击发送调用
onEditingCompleteText(controller.text);
Navigator.pop(context);
},
decoration: const InputDecoration(
hintText: '请输入评论的内容',
isDense: true,
contentPadding:
EdgeInsets.only(left: 10, top: 5, bottom: 5, right: 10),
border: OutlineInputBorder(
gapPadding: 0,
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
),
minLines: 1,
maxLines: 5,
),
),
)
],
),
);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//过度路由
import 'package:flutter/material.dart';
class PopRoute extends PopupRoute {
final Duration _duration = const Duration(milliseconds: 200);
Widget child;
PopRoute({required this.child});
@override
Color? get barrierColor => null;
@override
bool get barrierDismissible => true;
@override
String? get barrierLabel => null;
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return child;
}
@override
Duration get transitionDuration => _duration;
}
使用方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
GestureDetector(
onTap: () {
Navigator.push(
context,
PopRoute(
child: CommentWidget(
onEditingCompleteText: (text) {
print("text ==> $text");
},
),
),
);
},
child: Text(
'免责声明',
style: TxtStyle.titleS(color: const Color(0xffF29D2C)),
),
本文由作者按照 CC BY 4.0 进行授权