flutter - 将 TabBarView 中的其他选项卡更改为其他选项卡时,键盘仍然显示
问题描述
在一个选项卡中,我有一个 TextFormField,而在另一个选项卡中只有一个文本列表。当我选择文本字段时,键盘打开,然后我跳到第二个选项卡,键盘仍然显示。我什至可以写,当我回到 Tab 1 时,我明白了我为什么要打字。
您知道如何对第二个选项卡执行操作以将焦点从文本字段中移出吗?
DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Manage Products'),
bottom: TabBar(tabs: <Widget>[
Tab(icon: Icon(Icons.create), text: 'Create Product'),
Tab(icon: Icon(Icons.list), text: 'My Products'),
]),
),
body: TabBarView(
children: <Widget>[
ProductEditPage(addProduct: addProduct),
ProductListPage(products, updateProduct),
],
)),
);
解决代码
应用@nick.tdr 建议后,示例代码如下:
class _Test extends State<Test> with TickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: 2);
_tabController.addListener(() {
if (_tabController.indexIsChanging) {
FocusScope.of(context).requestFocus(new FocusNode());
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('2 Tabs'),
bottom: TabBar(controller: _tabController, tabs: <Widget>[
Tab(text: 'Tab with Text Field'),
Tab(text: 'Empty Tab'),
]),
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
Container(
child: TextFormField(
decoration: InputDecoration(labelText: 'Title'),
),
),
Container()
],
),
);
}
}
解决方案
您可以将手势检测器添加到脚手架并移除焦点。但这不适用于标签。对于选项卡,您需要执行以下操作:
controller.addListener((){
if(controller.indexIsChanging)
{
FocusScope.of(context).detach();
}
});
其中控制器是您的选项卡控制器。希望有帮助
推荐阅读
- html - CSS - 如何在不移动其他 div 的情况下将 div 放置在浏览器的中心
- javascript - 如何比较两个文本区域并检查 Javascript 中具有相同字符串和相同位置的重复项?
- java - Scala Monad - 没有 for 语句(检查空属性的优雅方式)
- c - 定位 RAM 变量的 ROM 地址
- spring - 配置服务器:本机属性源被忽略
- java - JSON:解析数组的 ArrayNode
- ubuntu - Docker 上 Ubuntu 的 root 密码是什么?
- javascript - Firebase:如何获取不匹配图像的差异并从存储中删除图像
- c++ - 绘制三角形的OpenGL程序给出了一个黄色的屏幕
- wordpress - 使用 OWASP ZAP 检测到 Wordpress SQL 注入