我想要一些 FormTextFields,其中包含一些用户可以更改的默认文本。 我遇到的问题是,一旦我修改了一个字段,如果我按下另一个字段或按钮,一切都很好,但是,如果我按下键盘上的“完成”按钮,就会返回默认文本, 删除用户插入的新的。这是我到目前为止所做的:
class _LoginSettingsViewState extends State<LoginSettingsView> {
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
var _userTextController = new TextEditingController();
@override
Widget build(BuildContext context) {
_userTextController.text = "test";
return Scaffold(
appBar: AppBar(
title: Text("Settings"),
),
body: ListView(
children: <Widget>[
new Container(
margin: EdgeInsets.only(
left: 10.0,
right: 10.0,
top: MediaQuery.of(context).size.height / 10
),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: _fieldDecoration("user", null),
controller: _userTextController,
validator: (val) => val.isEmpty ? "Insert user" : null,
onSaved: (val){
print(val);
},
),
最佳答案
您在 build 方法中设置默认文本,每次重建 UI 时,都会调用 build 方法,以便您放回默认文本。
在 initState
方法中进行初始化
@override
void initState() {
super.initState();
_userTextController.text = "test";
}
也不要忘记处理你的 Controller
@override
void dispose() {
_userTextController.dispose();
super.dispose();
}
关于dart - 具有默认文本的 TextFormField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295092/