带有默认文本的 TextFormField

Lit*_*key 0 dart flutter

我想要一些 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);
                      },
                    ),
Run Code Online (Sandbox Code Playgroud)

Had*_*ard 6

您在 build 方法中设置默认文本,每次重建 UI 时,都会调用 build 方法,因此您放回默认文本。

将您的初始化移动到initState方法中

@override
void initState() {
  super.initState();
  _userTextController.text = "test";
}
Run Code Online (Sandbox Code Playgroud)

也不要忘记处置您的控制器

@override
void dispose() {
  _userTextController.dispose();
  super.dispose();
}
Run Code Online (Sandbox Code Playgroud)