在 Flutter 中弹出时清除 TextField 中的文本 [英] Clear text in the TextField when pop in Flutter

查看:88
本文介绍了在 Flutter 中弹出时清除 TextField 中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a SearchText TextField. Since everything is working I want to know how to clear out the text in the text field when I come back to the same page. Right now, when I come back from the page the search text remains there.

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

Conditions: I'm passing the value from the field to the other page. So the search text should be having some text.

到目前为止我所做的是:

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

  • Tried to set the text to null after push happens. (I have button to go to another page)

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

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

Problem Occurred: The search text becomes null before pushing the data to another page. Which I don't want.

  • 试图在我的 initState() 中将文本设置为 null,但 pop 只是替换删除堆栈而不是重做页面.所以页面不会调用 initState()
  • Tried to set the text to null in my initState(), but pop just replaces removes the stack not redo the page. So the page doesn't call initState()

我也尝试这样做:

Navigator.of(context).pop('NoText': '');

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

But I don't know what to do in the home page for the search text, or update it.

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

第 1 页 ->第 2 页(按回)->第 1 页(搜索文本 = '')

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

Any help would be appreciated. Thanks :)

推荐答案

TextEditingController 添加到您的 TextField 并调用 controller.clear()> 只有在推送其他页面之后.

Add a TextEditingController to your TextField and call controller.clear() only after pushing the other page.

这可以通过在 onPressed 函数中使用 await 来完成,也可以使用 .then() 回调(如果需要)避免使您的 onPressed' 函数异步`.

This can be done either by using await inside the onPressed function or you can use the .then() callback if you want you avoid making your 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();
   });
}

让我知道这是否有帮助!

Let me know if this helps!

这篇关于在 Flutter 中弹出时清除 TextField 中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆