Form validator is not showing error in flutter why? - flutter

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.

remove value == from the condition it will work.
write like this
if (value == null || value.isEmpty)

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"))),
],
),
);
}
}

Related

I do all possible to solve that error Null check operator used on a null value I use (!) but there is error

class login extends StatelessWidget {
var emailController = TextEditingController();
var PasswordController = TextEditingController();
var _formKey = GlobalKey<FormState>();
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Login"),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: SingleChildScrollView(
child: Center(
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Login",
style: TextStyle(
fontSize: 40, fontWeight: FontWeight.bold)),
SizedBox(height: 40,),
TextFormField(
controller: emailController,
onFieldSubmitted: (String value) {
print(value);
},
onChanged: (String value) {
print(value);
},
validator: (String ?value) {
if (value == null || value.isEmpty) {
return 'the password must not be Empty';
}
return null;
},
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: "E-mail Address",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
prefixIcon: Icon(Icons.email),
),
),
SizedBox(height: 20,),
TextFormField(
controller: PasswordController,
obscureText: true,
keyboardType: TextInputType.visiblePassword,
validator: (String ?value) {
if (value == null || value.isEmpty) {
return 'the password must not be Empty';
}
return null;
},
onFieldSubmitted: (String value) {
print(value);
},
onChanged: (String value) {
print(value);
},
decoration: InputDecoration(
labelText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
prefixIcon: Icon(Icons.lock),
suffixIcon: Icon(Icons.remove_red_eye_rounded)
)
),
SizedBox(height: 20,),
defaultButton(
background: Colors.black26,
isUpperCase: true,
text: "Login",
function: () {
if (_formKey.currentState!.validate()) ==> // Null check operator
used on a null value.
{
print(emailController);
print(PasswordController);
}
}
),
SizedBox(height: 20,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Already you Have account?"),
TextButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) => Registry()));
},
child: Text("Register now "))
],
),
],
),
),
),
),
),
);
}
}
Hey what you're using is called the non-null assertion operator, it actually means you are saying that value can't be null. If you want to make sure it's not null before trying to access validate(), you should use optional chaining _formKey.currentState?.validate()
What you can also try to do is check that it's not null before you call validate().
if (!!_formkey.currentState && _formKey.currentState.validate())

Toggle password visibility using Gesture Detector

I'm new to flutter and following a tutorial where using an icon, the visibility of a password changes from hidden to visible.
I saw some cases where IconButton is used but even though I tried that method I'm still getting red lines everywhere. I wish to know where exactly the problem is unless it's a version related issue.
the variables are defined as such:
late String _password, _email;
bool _isObscure = true;
The Form Field
Widget _showPasswordInput() {
return TextFormField(
onSaved: (val) => _password = val!,
obscureText: _isObscure,
decoration: const InputDecoration(
// border: OutlineInputBorder(),
suffixIcon: GestureDetector(
onTap: () {
setState(() {
_isObscure = !_isObscure;
});
},
child: Icon(
_isObscure ? Icons.visibility : Icons.visibility_off,
),
),
labelText: 'Password',
hintText: 'Enter valid password, min: 6 chars',
icon: Icon(Icons.lock),
),
validator: (value) {
if (value!.isEmpty) {
return 'Please enter some text';
}
return null;
},
);
}
How it's used in the build
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Center(
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(children: <Widget>[
_showRegisterButton(),
]))),
)),
);
}
Inside InputDecoration, data is changing on runtime, therefore it cannot be const
decoration: InputDecoration(
// border: OutlineInputBorder(),
suffixIcon: GestureDetector(
onTap: () {
setState(() {
_isObscure = !_isObscure;
});
},
child: Icon(
_isObscure ? Icons.visibility : Icons.visibility_off,
),
),
and create a method like myTextFiled(BuildContext context) => TextFormField(....)

why is the form not validated? validator flutter form validation

import 'package:flutter/material.dart';
import 'package:sumanthk07/utilities/routes.dart';
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
#override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _formkey = GlobalKey<FormState>();
// ignore: avoid_types_as_parameter_names, non_constant_identifier_names
moveToHome(BuildContext) async{
Navigator.pushNamed(context, MyRoutes.homeRoute);
}
#override
Widget build(BuildContext context) {
return Material(
color: Colors.white,
child: SingleChildScrollView(
child: Form(
key: _formkey,
child: Column(
children: [
Image.asset("assets/images/login.png", fit: BoxFit.cover),
const SizedBox(
height: 20.0,
),
const Text(
'Welcome',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 32.0),
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(
hintText: "Enter User name", labelText: "Username "),
initialValue: "",
validator: (String? value) {
if (value !=null && value.isEmpty ) {
return "User name cannot be empty";
}
return null;
},
onChanged: (value) {
setState(() {});
},
),
TextFormField(
obscureText: true,
decoration: const InputDecoration(
hintText: "Enter password", labelText: "Password "),
initialValue: "",
validator: (String? value) {
if (value !=null && value.isEmpty ) {
return "Password name cannot be empty";
}
return null;
},
),
const SizedBox(
height: 20.0,
),
InkWell(
onTap: () => moveToHome(context),
child: AnimatedContainer(
duration: const Duration(seconds: 1),
height: 40,
width: 80,
alignment: Alignment.center,
child: const Text("Login",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18,
)),
decoration: BoxDecoration(
color: Colors.red,
// ignore: unnecessary_const
borderRadius: BorderRadius.circular(20)),
),
)
// ElevatedButton(
// child: const Text("Login"),
// style: TextButton.styleFrom(),
// onPressed: () {
// // ignore: unused_local_variable
// var myRoutes = MyRoutes;
// Navigator.pushNamed(context, MyRoutes.homeRoute);
// },
// )
],
),
)
],
),
),
),
);
}
BorderRadius newMethod() => BorderRadius.circular(20);
}
Hi All, I'm a beginner to flutter and I'm trying to add validator to widget but I'm not getting the validation when I run the application.
I searched and tried the ways to do it but I didn't get the desired outcome.
Can you guys look into my code and suggest the right way.
no errors found but validation is not working.
First assign TextEditingController to your both fields.
final TextEditingController _controllerUserName = TextEditingController();
final TextEditingController _controllerPassword = TextEditingController();
And also assign autovalidateMode to your text field so you can validate at user input like this. It's not necessary it's optional but you can add it to validate your field on input field changes. Although you can validate your form at submission time.
TextFormField(
decoration: const InputDecoration(
hintText: "Enter User name", labelText: "Username "),
initialValue: "",
validator: (String? value) {
if (value !=null && value.isEmpty ) {
return "User name cannot be empty";
}
return null;
},
onChanged: (value) {
setState(() {});
},
autovalidate : AutovalidateMode.onUserInteraction,
controller:_controllerUserName
),
And also you have not validate your form at submission time. try this
moveToHome(BuildContext) async{
if (_formkey.currentState.validate()) {
Navigator.pushNamed(context, MyRoutes.homeRoute);
}
}

Flutter form validation not working when checking phone number entered

I am trying to get form validation working, however, every time the form validates to true and I cannot work out why. Below is my code and every time I click "Save" the form validation passes even when the text box is empty.
There is a single validator for testing purposes checking if the contents of the text box is empty.
Any help would be greatly appreciated.
import 'package:flutter/material.dart';
class SignInScreen extends StatefulWidget {
#override
_SignInScreenState createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
// Form field state
String phoneNumber;
void validateAndSave() {
final FormState form = _formKey.currentState;
if (form.validate()) {
print('Form is valid');
} else {
print('Form is invalid');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.symmetric(
horizontal: 20.0,
vertical: 10.0,
),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(height: 10.0),
TextFormField(
validator: (value) {
value.isEmpty ? 'Enter a mobile phone number' : null;
},
keyboardType: TextInputType.phone,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(vertical: 15.0),
fillColor: Colors.white,
filled: true,
hintText: 'Mobile phone number',
prefixIcon: Icon(
Icons.phone_iphone,
size: 30.0,
),
),
onChanged: (value) {
setState(() => phoneNumber = value);
}),
SizedBox(height: 40.0),
FlatButton(
onPressed: () {
validateAndSave();
},
child: Text('Save'),
),
],
),
),
),
);
}
}
Solution is simple just add return keyword in the validator function.
import 'package:flutter/material.dart';
class SignInScreen extends StatefulWidget {
#override
_SignInScreenState createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
// Form field state
String phoneNumber;
void validateAndSave() {
final FormState form = _formKey.currentState;
if (form.validate()) {
print('Form is valid');
} else {
print('Form is invalid');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.symmetric(
horizontal: 20.0,
vertical: 10.0,
),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(height: 10.0),
TextFormField(
validator: (value) {
//Return a error string
return value.isEmpty ? 'Enter a mobile phone number' : null;
},
keyboardType: TextInputType.phone,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(vertical: 15.0),
fillColor: Colors.white,
filled: true,
hintText: 'Mobile phone number',
prefixIcon: Icon(
Icons.phone_iphone,
size: 30.0,
),
),
onChanged: (value) {
setState(() => phoneNumber = value);
}),
SizedBox(height: 40.0),
FlatButton(
onPressed: () {
validateAndSave();
},
child: Text('Save'),
),
],
),
),
),
);
}
}

How to make wrap content for ListView

I need to make dialog with form input fields and when i use with column content is fit to screen but when i try to type values it hiding the below input fields and submit button.Show to solve this issue i only know one soluction that replacing column with listview and works it allow me to scrool but the content is not fit to screen. How to make the content in listview fit to sceen?
Here is my full code
import 'package:devaayanam/Confi.dart';
import 'package:flutter/material.dart';
class BookPujaDialogContent extends StatefulWidget {
BookPujaDialogContent({Key key}) : super(key: key);
#override
_BookPujaDialogContentState createState() => _BookPujaDialogContentState();
}
class _BookPujaDialogContentState extends State<BookPujaDialogContent> {
final _formKey =GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Container(
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: Confi.TEMPLENAME
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.TEMPLENAME;
}
return null;
},
),
TextFormField(
decoration: InputDecoration(
labelText: Confi.DEITY
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.DEITY;
}
return null;
},
),
TextFormField(
decoration: InputDecoration(
labelText: Confi.BN
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.BN;
}
return null;
},
),
TextFormField(
decoration: InputDecoration(
labelText: Confi.STAR
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter '+Confi.STAR;
}
return null;
},
),
Container(
margin: EdgeInsets.only(top: 20),
child: RaisedButton(
onPressed: () {
// Validate returns true if the form is valid, or false
// otherwise.
if (_formKey.currentState.validate()) {
// If the form is valid, display a Snackbar.
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
}
},
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0D47A1),
Color(0xFF1976D2),
Color(0xFF42A5F5),
],
),
borderRadius: BorderRadius.all(Radius.circular(10.0))
),
width: MediaQuery.of(context).size.width,
height: 40,
// padding: const EdgeInsets.fromLTRB(45, 10, 45, 10),
child: Center(
child: Text(
Confi.BOOKNOW,
style: TextStyle(fontSize: 16)
),
),
),
),
)
],
),
),
);
}
}
Set shirinkWrap: true in ListView.
Dialog(
child: Form(
key: _formKey,
child: ListView(
shrinkWrap: true, //TODO: Use this
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: Confi.TEMPLENAME),
validator: (value) {
if (value.isEmpty) {
return 'Please enter ' + Confi.TEMPLENAME;
}
return null;
},
),
....
....