setState() clears the data in form element data flutter
With the given code, one mistake I can think of is creating TextEditingController
every time.
@override
Widget build(BuildContext context) {
var _textController = TextEditingController(); //problem
// build and return widgets
It should be in outside of build
method. We can have it in constructor
or initState
.
If you have _textController
outside build, can you add some more code?
Nagendra Badiganti
I’m an Android/Hybrid app developer with 8+ years experience with the Android SDK and Flutter. I have worked as a lead Mobile developer and I contributed to several open-source projects. You can find more details about my career and positions on my LinkedIn profile. https://www.linkedin.com/in/nagendra-badiganti I work from different locations in the world and I am reachable over Skype/email. I also provide different kinds of services, such as developing apps from scratch (IONIC, using the Android SDK/Flutter/react native), and adding/amending features in an existing Android app.
Updated on November 19, 2022Comments
-
Nagendra Badiganti over 1 year
I'm new to flutter and experimenting with Sateful widget. Here is the thing, In my UI screen layout, I have two different widgets
- DropdownButton widget
- TextFormField which holds card number.
When I was trying to update dropdown selected value to the DropdownButton widget, it automatically clears the text in TextFormField. Does it require to store text in global variable to restore again every time we call setState() method to update the values?
Here is the code for widgets, DropdownButton
new Padding( padding: const EdgeInsets.all(15.0), child: new Column( children: <Widget>[ DropdownButton<String>( value: _referPractice, isDense: true, hint: new Text(CONST_SELECT), items: _stdCodesList.map((value) { return new DropdownMenuItem<String>( value: value.dialCode, child: new Text("${value.code} ${value.dialCode}"), ); }).toList(), onChanged: (String newValue) { setState(() { _referPractice = newValue; // here I`m trying to update selected value. }); }, ) ], )),
TextFormField
TextFormField( controller: _textController, keyboardType: TextInputType.number, style: new TextStyle( fontWeight: FontWeight.w200, color: Colors.black, fontSize: 18.0, ), decoration: new InputDecoration( hintText: HING_ENTER_NUMBER, suffixIcon: CircleIconButton( onPressed: () { this.setState(() { _textController.clear(); }); }, )), maxLines: 1, validator: (value) { if (value.isEmpty) { return ERROR_CARD_DETAILS; } }, ),
I understand that Stateful widget rebuild the widget every time when ever it calls setState but how do I persist the data for form data which is not stored anywhere yet.
Suggestions please! Thanks in advance.
-
betteroutthanin over 4 yearsIs this the best approach that each typing triggers the build function?
-
Madian Malfi over 2 yearsif you want to assign text to _textController then do in initState