Reputation: 139
When I type a text and hit 'ok' or click the back button to hide the keyboard the input's value vanishes
Adding a TextEditingController
class ChatCepBottomSheet extends StatelessWidget {
final TextEditingController _cepController = TextEditingController();
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextFormField(
controller: _cepController,
),
SizedBox(height: 32),
Button(
buttonText: 'Search',
tapHandler: () {},
)
],
);
}
}
I expected that the typed text staid in the text controller
Upvotes: 1
Views: 6704
Reputation: 156
I had a similar problem. Not sure this is the solution, as other answers above have already proposed a solution, but what worked for me was; Removing the texteditingcontroller and using an onChanged instead
Upvotes: 0
Reputation: 171
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
Upvotes: 8
Reputation: 1109
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: () {},
)
],
)
);
}
}
Upvotes: 2
Reputation: 1898
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: () {},
)
],
);
}
}````
Upvotes: 5