Dart 具有默认文本的TextFormField

Dart 具有默认文本的TextFormField,dart,flutter,Dart,Flutter,我希望有一些FormTextFields,其中包含一些用户可以更改的默认文本。 我的问题是,一旦我修改了一个字段,如果我按下另一个字段或按钮,一切都很好,但是,如果我按下键盘上的“完成”按钮,然后返回默认文本,删除用户插入的新文本。这就是我到目前为止所做的: class _LoginSettingsViewState extends State<LoginSettingsView> { final GlobalKey<FormState> _formKey = ne

我希望有一些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);
                      },
                    ),
class\u LoginSettingsViewState扩展状态{
final GlobalKey _formKey=新GlobalKey();
var_userTextController=新的textededitingcontroller();
@凌驾
小部件构建(构建上下文){
_userTextController.text=“测试”;
返回脚手架(
appBar:appBar(
标题:文本(“设置”),
),
正文:ListView(
儿童:[
新容器(
页边距:仅限边距(
左:10.0,
右图:10.0,
顶部:MediaQuery.of(上下文).size.height/10
),
孩子:表格(
键:_formKey,
子:列(
儿童:[
TextFormField(
装饰:_fieldDecoration(“用户”,null),
控制器:_userTextController,
验证程序:(val)=>val.isEmpty?“插入用户”:null,
保存:(val){
打印(val);
},
),

您正在构建方法中设置默认文本,每次重新构建UI时,构建方法都是call,因此您将返回默认文本

将初始化移到
initState
方法中

@override
void initState() {
  super.initState();
  _userTextController.text = "test";
}
另外,不要忘记处置您的控制器

@override
void dispose() {
  _userTextController.dispose();
  super.dispose();
}

您在build方法中设置默认文本,每次重建UI时,build方法都是call,因此您将返回默认文本

将初始化移到
initState
方法中

@override
void initState() {
  super.initState();
  _userTextController.text = "test";
}
另外,不要忘记处置您的控制器

@override
void dispose() {
  _userTextController.dispose();
  super.dispose();
}

oooops,你是对的,当我编写这段代码时,我脑子里发生了一些完全错误的事情。非常感谢!
super.initState()
应该始终是
initState()
method.oooops,你是对的,当我编写这段代码时,我脑子里发生了一些完全错误的事情。非常感谢!
super.initState()
应该始终是在
initState()方法中执行的第一行。