Reputation: 1012
Please help for my 2 questions.
1st Question. Why text value disappear?[FIXED] by @Praneeth I added gif please click
I used this way my code,
In my widget I called UsernameTextField
class.
Widget looks like this,
Widget build > WillPopScope > Scaffold > Form > ListView > children> Container (below container) I added
key: _scaffoldKey,
andkey: formKey,
also.
Container(
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.only(top: 30.0),
child: UsernameTextField(),
),
UsernameTextField()
class UsernameTextField extends StatefulWidget{
final usernameController = TextEditingController();
@override
State<StatefulWidget> createState() {
return UsernameTextFieldState(usernameController);
}
}
class UsernameTextFieldState extends State<UsernameTextField>{
final usernameController;
UsernameTextFieldState(this.usernameController);
@override
Widget build(BuildContext context) {
return AppTextField(
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(20.0),
labelText: AppTranslations.of(context)
.text("loginpage_username"),
),
myController: usernameController,
textInputType: TextInputType.emailAddress
);
}
}
AppTextField() class, I used this class for my every TextField Widget
class AppTextField extends StatelessWidget {
final InputDecoration decoration;
final myController;
final TextInputType textInputType;
AppTextField({
this.decoration,
this.myController,
this.textInputType
});
@override
Widget build(BuildContext context) {
return TextFormField(
controller: myController,
keyboardType: textInputType,
textAlign: TextAlign.left,
decoration: decoration
);}}
2nd Question. How to get textField value?
In my button onPressed()
method I called, I called validation
method, But result is null
usernameValidation(){
String username = UsernameTextField().usernameController.text;
print(username);
}
Upvotes: 0
Views: 1060
Reputation: 3263
First convert UsernameTextField class to a Stateful one by extending as a StatefulWidget instead of StatelessWidget.
Then you can get value from usernameController.text
UPDATE
class UsernameTextField extends StatefulWidget{
final usernameController = TextEditingController();
UsernameTextField(this.usernameController)
@override
State<StatefulWidget> createState() {
return UsernameTextFieldState(usernameController);
}
}
class UsernameTextFieldState extends State<UsernameTextField>{
@override
Widget build(BuildContext context) {
return AppTextField(
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(20.0),
labelText: AppTranslations.of(context)
.text("loginpage_username"),
),
myController: widget.usernameController,
textInputType: TextInputType.emailAddress
);
}
}
Upvotes: 1