I created form when i click on button to validate validator not showing error.
GlobalKey<FormState> formkey= GlobalKey<FormState>();
Created Global Key in my code
Form(
key: formkey,
child: ListView(
scrollDirection: Axis.vertical,
children: [
Padding(
padding: const EdgeInsets.all(20),
child: TextFormField(
controller: _name,
validator: (value) {
if (value == null || value == value.isEmpty) {
return "Enter Name";
}
return null;
},
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(),
labelText: "Name",
prefixIcon: Icon(Icons.person),
errorStyle: TextStyle(color: Colors.red)),
),
),
I created form
Center(
child: ElevatedButton(
onPressed: () {
if (formkey.currentState!.validate()) {
setState(() {
name = _name.text;
email = _email.text;
password = _password.text;
});
addUser();
clear();
}
},
child: Text("Register"))),
Code of button This is the code help me.
CodePudding user response:
remove value == from the condition it will work. write like this
if (value == null || value.isEmpty)
CodePudding user response:
I solved your answer like this:
import 'package:flutter/material.dart';
class MyStackAns extends StatefulWidget {
const MyStackAns({super.key});
@override
State<MyStackAns> createState() => _MyStackAnsState();
}
class _MyStackAnsState extends State<MyStackAns> {
GlobalKey<FormState> formkey = GlobalKey<FormState>();
final TextEditingController _name = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Stack Answers'),
),
body: Column(
children: [
Form(
key: formkey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Padding(
padding: const EdgeInsets.all(20),
child: TextFormField(
controller: _name,
validator: (value) {
if (value == null || value.isEmpty) {
return "Enter Name";
}
return null;
},
decoration: const InputDecoration(
enabledBorder: OutlineInputBorder(), focusedBorder: OutlineInputBorder(), labelText: "Name", prefixIcon: Icon(Icons.person), errorStyle: TextStyle(color: Colors.red)),
),
),
),
Center(
child: ElevatedButton(
onPressed: () {
if (formkey.currentState!.validate()) {
//Perform your validate task here
}
},
child: const Text("Register"))),
],
),
);
}
}