我想为文本字段提供一个初始值,并重新绘制一个空值以清除文本。用Flutter的api实现这一点的最佳方法是什么?
当前回答
(来自邮件列表。这个答案不是我想出来的。)
class _FooState extends State<Foo> {
TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = new TextEditingController(text: 'Initial value');
}
@override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new TextField(
// The TextField is first built, the controller has some initial text,
// which the TextField shows. As the user edits, the text property of
// the controller is updated.
controller: _controller,
),
new RaisedButton(
onPressed: () {
// You can also use the controller to manipuate what is shown in the
// text field. For example, the clear() method removes all the text
// from the text field.
_controller.clear();
},
child: new Text('CLEAR'),
),
],
);
}
}
其他回答
我在这里见过很多方法。然而,我认为这比其他答案更有效或至少更简洁。
TextField(
controller: TextEditingController(text: "Initial Text here"),
)
内部类,
final usernameController = TextEditingController(text: 'bhanuka');
文本框,
child: new TextField(
controller: usernameController,
...
)
这可以通过使用TextEditingController来实现。
要有一个初始值,你可以加上
TextEditingController _controller = TextEditingController(text: 'initial value');
or
如果你正在使用TextFormField,你有一个initialValue属性。它基本上自动地将这个initialValue提供给小部件。
TextFormField(
initialValue: 'initial value'
)
清除文本可以使用 _controller.clear()方法。
你不需要在小部件范围内定义一个单独的变量,只需内联即可:
TextField(
controller: TextEditingController()..text = 'Your initial value',
onChanged: (text) => {},
)
TextEdittingController _controller = new TextEdittingController(text: "your Text");
or
@override
void initState() {
super.initState();
_Controller.text = "Your Text";
}