简体   繁体   中英

TextFormField with default text

I want to have some FormTextFields with some default text inside that the user can change. 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.

move you initialization inside initState method

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

also don't forget to dispose your controller

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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