首页 > 解决方案 > TextField 的自动对焦属性导致小部件进入“脏”状态

问题描述

AppBar 有一个搜索图标,单击它会在“标题”属性中显示一个 TextField。单击搜索图标时,我需要 TextField 自动对焦。问题在于“autofocus”属性,如果设置为 true,而不是仅更改 title 属性的状态,某些东西会导致小部件变成“脏”状态。这会导致调用主构建函数,从而重建整个事物。

试图复制它并提供一个示例应用程序,但奇怪的是它在演示中似乎工作得很好。

有什么调试建议吗?

     AppBar(
                  centerTitle: true,
                  title: StreamBuilder(
                      stream: false,
                      initialData: symbolBloc.isSearching,
                      builder: (BuildContext context, AsyncSnapshot<bool> snapshot){
                        if(snapshot.data) {
                          return TextField(
    //                        autofocus: true, <--- here
                            controller: searchQuery,
                            style: new TextStyle(
                              color: Colors.white,
                            ),
                          );
                        }

                        return new Text("", style: new TextStyle(color: Colors.white)
                        );
                      }),
                  backgroundColor: Colors.blueGrey,
                  elevation: 0.0,
                  actions: <Widget>[
                    StreamBuilder(
                      stream: bloc.isSearchActive,
                      initialData: false,
                      builder: (BuildContext context, AsyncSnapshot<bool> snapshot){
                        if(snapshot.data)
                            return activeSearchIconButton(symbolBloc);
                        return searchIconButton(symbolBloc);
                      },

                    ),
                  ],
                ),

 searchIconButton(SymbolBloc bloc){
    return new IconButton(
      icon: new Icon(
        Icons.search,
        color: Colors.white,
      ),
      tooltip: 'Search',
      onPressed: (){
        bloc.displaySearchField(true);
      },
    );
  }

  activeSearchIconButton(SymbolBloc bloc){
    return new IconButton(
      icon: new Icon(
        Icons.close,
        color: Colors.white,
      ),
      tooltip: 'Search',
      onPressed: (){
        bloc.displaySearchField(false);
      },
    );
  }

标签: dartflutter

解决方案


您可以设置FocusNode属性TextFieldButton点击调用FocusScope.of(context).requestFocus(_focusNode);


推荐阅读