why is the form not validated? validator flutter form validation

1k Views Asked by At
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.

1

There are 1 best solutions below

0
On BEST ANSWER

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);
   }
 }