Text input value is disappearing Flutter
Solution 1:
What you are trying to do will not work with Flutter. You are using a stateless
widget and trying to preserve state (data), which is impossible by definition. You need to rewrite your class using a stateful
widget - https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html.
See an example below:
import 'package:flutter/material.dart';
class ChatCepBottomSheet extends StatefulWidget {
@override
_ChatCepBottomSheetState createState() => _ChatCepBottomSheetState();
}
class _ChatCepBottomSheetState extends State<ChatCepBottomSheet> {
final TextEditingController _cepController = TextEditingController();
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextFormField(
controller: _cepController,
),
SizedBox(height: 32),
Button( //choose a button class or custom class
buttonText: 'Search',
tapHandler: () {},
)
],
);
}
}````
Solution 2:
When keyboard opens it changes the screen behavior and when we close it it re renders the screen and due to that this field initialized again by empty constructor.
TextEditingController _cepController = TextEditingController();
Stateful or stateless it doesnt matter if you are in this kind of issue like keyboard opening etc
try defining final TextEditingController _cepController = TextEditingController();
outside of this class
Solution 3:
The declaration of the "Button" is wrong. Check the Docs for more information. Plus, you can't preserve the state in a StatelessWidget
.
This will help:
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final TextEditingController _cepController = TextEditingController();
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: Text('Demo')),
body: Column(
children: <Widget>[
TextFormField(
controller: _cepController,
),
SizedBox(height: 32),
FlatButton(
child: Text('Search'),
onPressed: () {},
)
],
)
);
}
}