Flutter设置textfield的值

9

我是Flutter的新手。我有一个联系人列表项目(姓名,电话,地址),当用户点击联系人时,我将其发送到编辑表单,并且想用联系人数据填充表单。 我使用TextField作为输入,并通过小部件获取数据,例如:widget.contact.data['name']。 我无法找到此问题的任何答案。


展示一些代码。可以使用TextEditingController来添加项目。 - nonybrighto
请提供 [mcve]。 - Nae
1个回答

24

在Flutter的docs中,有两种访问TextField文本的方法。

第一种是通过onChanged回调函数,它有一个参数是当前的文本。

TextField(
  onChanged: (text) {
    // do what you want with the text
  },
);

如果需要更高级的文本处理,包括从build()方法之外访问它,则可以使用TextEditingController

final _controller = TextEditingController();

然后您可以将其链接到您的TextField:

TextField(
  // other parameters
  controller: _controller,
);

不要忘记处理它!

@override
void dispose() {
  // other dispose methods
  _controller.dispose();
  super.dispose();
}

现在,您可以通过访问`_controller.text`的值或修改它来设置或获取文本。例如:
获取:`print(_controller.text);`
设置:`_controller.text = 'newText' // 现在TextField中将写入'newText'`
或者,您可以使用`addListener`监听更改,因此每当更新文本时,将调用您选择的函数:
@override
void initState() {
    super.initState();
    _controller.addListener(_handleText);
    // other code here
}

_handleText() {
   // do what you want with the text, for example:
   print(_controller.text);
}

谢谢,它起作用了。我使用了TextEditingController,在initState中,我使用联系人列表中的值加载了控制器,这解决了我的问题。 - Rafael Honda
@RafaelHonda 如果这个答案对您有帮助,请点击勾选标记接受它。请查看此链接获取更多详细信息-> https://stackoverflow.com/help/someone-answers - Amsakanna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接