在 Flutter 中弹出时清除 TextField 中的文本

Alo*_*lok 1 uitextfield flutter

我有一个SearchText文本字段。由于一切正常,我想知道当我回到同一页面时如何清除文本字段中的文本。现在,当我从页面返回时,搜索文本仍然存在。

条件:我将字段中的值传递到另一个页面。所以搜索文本应该有一些文本。

到目前为止我所做的是:

  • 尝试在推送发生后将文本设置为 null。(我有按钮可以转到另一个页面)

    onPressed: (){
       Navigator.push(context, new MaterialPageRoute(
         builder: (context) => SearchPage(searchText: this.search.text)
       ));
       setState((){this.search.text = '';});
    }
    
    Run Code Online (Sandbox Code Playgroud)

发生的问题:在将数据推送到另一个页面之前,搜索文本变为空。我不想要的。

  • 试图在 my 中将文本设置为 null initState(),但 pop 只是替换删除堆栈而不是重做页面。所以页面不会调用initState()

我也尝试这样做:

Navigator.of(context).pop('NoText': '');
Run Code Online (Sandbox Code Playgroud)

但是我不知道在主页中为搜索文本做什么,或者更新它。

我不想再次推送,因为它会再次将同一页面添加到堆栈中。

Page 1 -> Page 2 (press back) -> Page 1 (search text = '')

任何帮助,将不胜感激。谢谢 :)

Sid*_*kar 7

仅在推送其他页面后才将a 添加TextEditingController到您的TextField和调用controller.clear()

这可以通过awaitonPressed函数内部使用来完成,或者.then()如果您希望避免使用onPressed' functionasync`,则可以使用回调。

例子 -

//Initialize a controller inside your State class
TextEditingController _controller = TextEditingController();

//Set the _controller on you TextField
TextField(
  controller: _controller,
  //Rest of your code
)

//Clear the controller after pushing the new page
onPressed: () {
   Navigator.push(context, new MaterialPageRoute(
     builder: (context) => SearchPage(searchText: this.search.text)
   )).then((value) {
      //This makes sure the textfield is cleared after page is pushed.
      _controller.clear();
   });
}
Run Code Online (Sandbox Code Playgroud)

让我知道这是否有帮助!