我想为文本字段提供一个初始值,并重新绘制一个空值以清除文本。用Flutter的api实现这一点的最佳方法是什么?
当前回答
你可以使用TextFormField代替TextField,并使用initialValue属性。例如
TextFormField(initialValue: "I am smart")
其他回答
如果你使用TextEditingController只需要在你的类中使用这一行。
TextEditingController txtController = TextEditingController(text: 'Initial value')
TextField(
controller: txtController,
);
如果你不使用TextEditingController就去initialValue
TextFormField(
initialValue: 'your initial text',
);
完整代码
class _TestScreen extends State<Test> {
TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = new TextEditingController(text: 'Initial value');
}
@override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
TextField( // First method
initialValue: "Initial text"
),
TextField( // Second method
controller: _controller, // Controller has the initial value
),
],
);
}
}
我在这里见过很多方法。然而,我认为这比其他答案更有效或至少更简洁。
TextField(
controller: TextEditingController(text: "Initial Text here"),
)
你不需要在小部件范围内定义一个单独的变量,只需内联即可:
TextField(
controller: TextEditingController()..text = 'Your initial value',
onChanged: (text) => {},
)
如果您使用文本表单字段并将数据从上一页传递到下一页文本表单字段,请使用此选项
class ProfilePage extends StatefulWidget {
late final String fname;
ProfilePage({required this.fname});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
final _form = GlobalKey<FormState>();
late var FullNameController = TextEditingController(text: widget.fname);
}
内部类,
final usernameController = TextEditingController(text: 'bhanuka');
文本框,
child: new TextField(
controller: usernameController,
...
)