Reputation: 217
When a TextFormField
is filled in, the input vanishes when clicking off. It is within a StatefulWidget
.
I'm guessing this has something to do with state?.. I am using identical logic to another page in the application, yet I can't get this page to work.
class EditContact extends StatefulWidget {
EditContact({Key key, @required this.contact}) : super(key: key);
final Contact contact;
@override
_EditContactState createState() => _EditContactState();}
class _EditContactState extends State<EditContact> {
@override
Widget build(BuildContext context) {
final oneController = TextEditingController();
final twoController = TextEditingController();
final threeController = TextEditingController();
final fourController = TextEditingController();
final fiveController = TextEditingController();
final sixController = TextEditingController();
final sevenController = TextEditingController();
...
TextFormField(
controller: oneController,
decoration: textInputDecoration.copyWith(hintText: 'Name'),
),
Upvotes: 0
Views: 419
Reputation: 4995
you should not initialize controllers inside of the build method!
The problem is that with the code above you are re-creating a new controller (with no text) every time the page is built again and this is clearing the text field. To fix that, initialize your controllers out of the build method.
class EditContact extends StatefulWidget {
EditContact({Key key, @required this.contact}) : super(key: key);
final Contact contact;
@override
_EditContactState createState() => _EditContactState();}
class _EditContactState extends State<EditContact> {
final oneController = TextEditingController();
final twoController = TextEditingController();
final threeController = TextEditingController();
final fourController = TextEditingController();
final fiveController = TextEditingController();
final sixController = TextEditingController();
final sevenController = TextEditingController();
@override
void dispose() {
// dispose your controllers here
super.dispose();
}
@override
Widget build(BuildContext context) {
// ..... your code
}
}
Note that you can initialize your controllers inside of the initState as well!
Upvotes: 3