Flutter中如何在键盘弹出时将Widget置于键盘顶部(仿TikTok评论)
在Flutter的Get.bottomSheet中实现评论输入框跟随键盘顶部的方案
要实现TikTok风格的评论输入框(键盘弹出时自动贴在键盘顶部),你需要调整Get.bottomSheet的配置和布局结构,具体改动如下:
核心改动点
- 开启
isScrollControlled: true:让BottomSheet能够自适应键盘高度,自动向上调整位置 - 调整布局结构:将评论列表区域改为可滚动组件,输入框区域固定在底部(不再使用Expanded占据剩余空间)
修改后的完整代码
onTap: () { Get.bottomSheet( // 用SingleChildScrollView包裹,确保内容在键盘弹出时可滚动 SingleChildScrollView( child: Container( // 用MediaQuery获取屏幕高度,确保BottomSheet初始高度为屏幕的70% height: MediaQuery.of(context).size.height * 0.7, width: MediaQuery.of(context).size.width, decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), ), ), child: Column( children: [ // 评论计数栏:固定高度 SizedBox( height: MediaQuery.of(context).size.height * 0.1, child: Center( child: Text("${widget.video["commentsCount"]} comments"), ), ), // 评论列表区域:用Expanded+SingleChildScrollView实现滚动 Expanded( child: SingleChildScrollView( child: Text("BODY"), // 这里替换为你的评论列表Widget ), ), // 输入框区域:固定高度,不再用Expanded SizedBox( height: MediaQuery.of(context).size.height * 0.1, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Row( children: [ Container( height: iconSize, width: iconSize, decoration: BoxDecoration( border: Border.all(color: Colors.white), borderRadius: BorderRadius.circular(25), image: DecorationImage( image: NetworkImage( widget.video['user']['profilePic'] == "" ? 'https://picsum.photos/id/1062/400/400' : widget.video['user']['profilePic'], ), ), ), ), SizedBox(width: MediaQuery.of(context).size.width * 0.02), Expanded( child: Container( margin: EdgeInsets.symmetric( vertical: MediaQuery.of(context).size.height * 0.015, ), padding: EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.03, ), decoration: BoxDecoration( color: Colors.grey[100], borderRadius: BorderRadius.circular(50), ), child: Row( children: [ const Expanded( child: TextField( decoration: InputDecoration( border: InputBorder.none, hintText: "Add comments...", ), ), ), IconButton( onPressed: () {}, icon: const Icon( Icons.send, color: Colors.tealAccent, ), ) ], ), ), ) ], ), ), ), ], ), ), ), // 关键参数:开启自适应键盘高度 isScrollControlled: true, // 可选:设置背景透明度 backgroundColor: Colors.transparent, ); },
关键说明
- isScrollControlled: true:这是实现输入框跟随键盘的核心,它会让BottomSheet的高度自动适配当前可用空间(包括键盘弹出后的剩余空间),从而让输入框自然贴在键盘顶部。
- 布局调整:
- 评论计数栏和输入框都设置了固定高度,避免Expanded在BottomSheet高度变化时打乱布局。
- 评论列表区域用
Expanded + SingleChildScrollView实现,确保评论内容在键盘弹出后仍可滚动查看。
- 移除不必要的透明文字:原代码中TextField的
style: TextStyle(color: Colors.transparent)会导致输入内容不可见,建议移除。
这样修改后,当用户点击输入框唤起键盘时,整个BottomSheet会向上调整,输入框会自动贴在键盘顶部,完全复刻TikTok的评论交互效果。
内容的提问来源于stack exchange,提问作者Mohammed Bekele
相关产品推荐
相关产品推荐

