【问题标题】:errors when clearing TextField flutter清除 TextField 抖动时的错误
【发布时间】:2019-11-25 07:45:39
【问题描述】:

我正在尝试清除我的 TextField,这就是我要做的

IconButton(
      onPressed: (){
        FocusScope.of(context).requestFocus(new FocusNode());
        _searchFieldController.clear();
        setState(() {
          searchClicked = false;
        });
      },
      icon: Icon(Icons.close),
    );
  }

当我运行它时,我得到了这个错误

I/flutter (4547): ══╡ 手势捕捉到的异常 ╞═════════════════════════════════════════════════ ══════════════════ I/flutter (4547):在处理 手势:I/flutter(4547):无效的文本选择: TextSelection(baseOffset: 6, extentOffset: 6, affinity: I/flutter ( 4547): TextAffinity.upstream, isDirectional: false)

这是我的小部件

TextField(
                  onChanged: (text) {
                    if(text.length >= 4){
                      searchResult = productTemp.where((i) => i.productName.contains(text.toString())).toList();
                      _productController.sink.add(searchResult);
                    }else{
                      _productController.sink.add(productTemp);
                    }
                  },
                  focusNode: _focus,
                  controller: _searchFieldController,
                  style: TextStyle(fontSize: 15),
                  decoration: InputDecoration(
                      filled: true,
                      hintStyle:new TextStyle(color: Colors.grey[800],fontSize: 20),
                      fillColor: Colors.white70,
                      hintText: "Search",
                      suffixIcon: searchClicked  ? buildCancelIcon() : buildSearchIcon()
                  ),
                )

【问题讨论】:

    标签: flutter


    【解决方案1】:

    https://github.com/flutter/flutter/issues/17647

    WidgetsBinding.instance.addPostFrameCallback((_) => _searchFieldController.clear());
    

    【讨论】:

    • 为我工作+1;我用它作为对来自 TextFormField 装饰的 IconButton 点击​​的响应。
    【解决方案2】:

    参考:https://github.com/flutter/flutter/issues/35848

    Future.delayed(
        Duration(milliseconds: 50),
    ).then(
        (_) {
            _suburbSearchController.clear();
        },
    );
    

    在上面的参考中,有两种方式,包括WidgetsBinding

    我更喜欢delayed,因为有人在WidgetsBinding 解决方法中提到了“...多次添加相同的回调(例如每次构建小部件时添加一个侦听器)...”。

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 2021-09-20
      • 2022-06-12
      • 2013-05-08
      • 2020-09-06
      • 2020-04-21
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多