When the save button is pressed, if the form is valid it will be saved successfully, but if it is not valid you will get error message "Please resolve given errors" and under every required field there is error message 'required Field'. I want to add the names of required fields that are not filled to the message that shows when save button is pressed (to this message "Please resolve given errors"). How I can do that?
here is the submit function
void _submit() {
if (_formKey.currentState.validate()) {
_save();
}
else if (!_formKey.currentState.validate()) {
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text("Please resolve given errors")
));
return;
}
_formKey.currentState.save();}
here is one of my TextFormField
TextFormField(
decoration: InputDecoration(
labelText:
AppLocalizations.of(context)
.getTranslated('firstName'),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(
5.0))),
controller: firstNameController,
validator: (String value) {
if (value.isEmpty) {
return AppLocalizations.of(context)
.getTranslated('requiredField');
}
return null;
},
onChanged: (value) {
debugPrint(
'Something changed in Username Text Field');
user.firstName =
firstNameController.text;
},
)
CodePudding user response:
You can work with validation or errorText. I Like work with errorText and validation in separate method.
First, create a validation method:
String? validateEmail(String? value){
if ((value??'').isEmpty){
setState(()=>{emailError = 'Cannot be empty'});
} else {
setState(()=>{emailError = ''});
}
return emailError;
}
So.. in your TextFormField put a errorText.
TextFormField(
style: const TextStyle(fontSize: 16.0, color: Colors.black),
decoration: InputDecoration(
errorText: (emailError != null &&( emailError??'').isEmpty )? null :emailError.toString(),
),
controller: _myController,
)
In button click you call the validation method.
CodePudding user response:
I made a minimal example of what you want:
I don't think you need the textController.
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _formKey = GlobalKey<FormState>();
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
Map<String, String> values = {"name": "", "age": "", "number": ""};
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
body: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: ((value) {
if (value!.isEmpty) return "Required Field";
}),
onChanged: ((v) {
values.update("name", (value) => v);
}),
),
TextFormField(
validator: ((value) {
if (value!.isEmpty) return "Required Field";
}),
onChanged: ((v) {
values.update("age", (value) => v);
}),
),
TextFormField(
validator: ((value) {
if (value!.isEmpty) return "Required Field";
}),
onChanged: ((v) {
values.update("number", (value) => v);
}),
),
TextButton(
onPressed: () {
_submit(values);
},
child: Text("Submit"))
],
)),
);
}
void _submit(Map<String, String> values) {
if (_formKey.currentState!.validate()) {
// _save();
} else if (!_formKey.currentState!.validate()) {
var list =
values.entries.where((element) => element.value.isEmpty).toList();
if (list.length == 1) {
_scaffoldKey.currentState!
.showSnackBar(SnackBar(content: Text("${list[0].key} is empty")));
} else if (list.length == 2) {
_scaffoldKey.currentState!.showSnackBar(SnackBar(
content: Text("${list[0].key} and ${list[1].key} are empty")));
} else if (list.length == 3) {
_scaffoldKey.currentState!.showSnackBar(SnackBar(
content: Text(
"${list[0].key},${list[1].key},and ${list[2].key} are empty")));
}
}
_formKey.currentState!.save();
}
}
CodePudding user response:
Declare a List of String
List<String> hintList = [];
Then in textFormField validator check if the value is empty, then add the hint to hintList
TextFormField(
decoration: InputDecoration(
labelText: "First name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
controller: firstNameController,
validator: (value) {
if (value == null || value.isEmpty) {
if(!hintList.contains("First name")){
hintList.add("First name");
}
return 'Required field!';
}
if (hintList.contains("First name")) {
hintList.removeWhere((element) => element == "First name");
}
return null;
},
onChanged: (value) {
user.firstName = firstNameController.text;
},
)
Then on Save button pressed, put onSubmit function. if formkey not validate then show hintlist empty, else call save() func
void submit() {
if (formKey.currentState!.validate()) {
save();
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("${hintList.join(", ")} fields empty!"),
duration: const Duration(milliseconds: 500),
));
}
}