gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:20:24 27 4
gpt4 key购买 nike

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

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

到目前为止我所做的是:

  • 尝试在推送发生后将文本设置为空。 (我有按钮去另一页)

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

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

  • 尝试在我的 initState() 中将文本设置为 null,但弹出只是替换并移除堆栈而不是重做页面。所以页面不会调用initState()

我也试过这样做:

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

但是对于搜索文本,我不知道在首页做什么,或者更新一下。

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

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

如有任何帮助,我们将不胜感激。谢谢:)

最佳答案

TextEditingController 添加到您的 TextField 并仅在推送另一个页面后调用 controller.clear()

这可以通过在 onPressed 函数中使用 await 来完成,或者如果需要,您可以使用 .then() 回调避免让你的 onPressed 函数 async

例子-

//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();
});
}

如果这有帮助,请告诉我!

关于flutter - 在 Flutter 中弹出时清除 TextField 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003178/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com