Using forms, I want to create a reusable TextFormField but I don’t get the Save value on my Main widget. I don’t want write same style for every TextFormField and which will make the page lengthy so I decided to create a widget and call it where needed.
Reusable TextFormField Code
class AuthTextfields extends StatelessWidget {
const AuthTextfields(
{super.key,
required this.inputType,
required this.autoCorrect,
required this.enableSuggestion,
required this.labTxt,
required this.iconData,
required this.saveTxt,
required this.vaildCheck,
required this.formGlobal});
final TextInputType inputType;
final bool autoCorrect;
final bool enableSuggestion;
final String labTxt;
final IconData iconData;
final String Function(String vaildTxt) vaildCheck;
final void Function(String txt) saveTxt;
final Key formGlobal;
@override
Widget build(BuildContext context) {
return Form(
key: formGlobal,
child: TextFormField(
style: TextStyle(color: Colors.white),
keyboardType: inputType,
autocorrect: autoCorrect,
enableSuggestions: enableSuggestion,
decoration: InputDecoration(
labelText: labTxt,
border: const OutlineInputBorder(),
prefixIcon: Icon(
iconData,
color: Theme.of(context).colorScheme.primary,
)),
validator: (value) {
return vaildCheck(value!);
},
onSaved: (newValue) => saveTxt(newValue!),
),
);
}
}
Try to getting the Data by below code:
final formGlobal = GlobalKey<FormState>();
String userName = "";
AuthTextfields(
inputType: TextInputType.name,
autoCorrect: false,
enableSuggestion: false,
labTxt: "User Name",
iconData: Icons.account_circle_rounded,
vaildCheck: (value) {
if (value == "" ||
value.trim().isEmpty ||
value.trim().length < 3) {
return "Please add A Valid Name with at least 3 Character";
}
return "";
},
formGlobal: formGlobal,
saveTxt: (String txt) {
setState(() {
userName == txt;
});
},
),
const Gap(20),
ElevatedButton.icon(
onPressed: () {
final isValid = formGlobal.currentState!.validate();
FocusScope.of(context).unfocus();
if (!isValid) {
return;
}
formGlobal.currentState!.save;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("hello$userName")));
},
label: const Text("Save"),
),
Why ScaffoldMessenger can’t show the value I input on TextField?
2
Answers
Change the value assignment while set your username in AuthTextfields saveTxt code.
Your code is:
Change the code using the assignment keyword (
=
). Not the equal to operator (==
). Like below:Hopefully it can solve your problem, Thanks 😉
Here are some fixes and improvements for your Flutter code:
Fixing the saveTxt Callback: In the saveTxt callback of AuthTextfields, you are using the equality operator (==) instead of the assignment operator (=) to update the userName. Also, make sure to call setState to update the state of your widget tree.
Correctly Calling save in the Form: You need to call the save method on the form key (formGlobal.currentState!.save()), not just accessing it directly.
Here’s the updated code with these fixes: