简体   繁体   English

具有默认文本的TextFormField

[英]TextFormField with default text

I want to have some FormTextFields with some default text inside that the user can change. 我想拥有一些FormTextFields,其中包含一些用户可以更改的默认文本。 The problem that I have is that, once I have modified a field, if I press to another field or a button, everything is good, but, if I press on the "complete" button on the keyboard, then came back the default text, deleting the new one inserted by the user. 我的问题是,修改了字段后,如果按一下另一个字段或按钮,一切都很好,但是,如果按键盘上的“完成”按钮,则会返回默认文本,删除用户插入的新内容。 This is what I've done so far: 到目前为止,这是我所做的:

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);
                      },
                    ),

You are setting the default text inside build method, each time you rebuild the UI, the build method is call so you put back the default text. 您是在build方法中设置默认文本,每次重新构建UI时,都会调用build方法,因此您可以放回默认文本。

move you initialization inside initState method 将您的初始化initState方法中

@override
void initState() {
  super.initState();
  _userTextController.text = "test";
}

also don't forget to dispose your controller 也不要忘记布置控制器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM