首页 > 解决方案 > 将 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),
            ],
          )),
    );

选项卡1

选项卡2

解决代码

应用@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()
        ],
      ),
    );
  }
}

标签: flutter

解决方案


您可以将手势检测器添加到脚手架并移除焦点。但这不适用于标签。对于选项卡,您需要执行以下操作:

controller.addListener((){

  if(controller.indexIsChanging)
    {
      FocusScope.of(context).detach();
    }
});

其中控制器是您的选项卡控制器。希望有帮助


推荐阅读