Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Form Validation Error #28

Open
sid86-dev opened this issue Jul 24, 2021 · 3 comments
Open

Form Validation Error #28

sid86-dev opened this issue Jul 24, 2021 · 3 comments

Comments

@sid86-dev
Copy link

sid86-dev commented Jul 24, 2021

After clicking Login button the screen is changing even if the text and password fields are empty

import 'package:first_app/utils/approutes.dart';
import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  String name = "";
  bool changebtn = false;
  final _formkey = GlobalKey<FormState>();

  movetohome(BuildContext context) async {
    if (_formkey.currentState!.validate()) {
      setState(() {
        changebtn = true;
      });
    }
    // push to move to next route

    await Future.delayed(Duration(seconds: 1));
    await Navigator.pushNamed(context, Approutes.homeRoute);
    setState(() {
      changebtn = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        color: Colors.white,
        child: SingleChildScrollView(
          child: Form(
            key: _formkey,
            child: Column(
              children: [
                Image.asset(
                  "assets/images/top.png",
                  fit: BoxFit.cover,
                ),
                SizedBox(
                  height: 80.0,
                ),
                Text(
                  "Welcome $name",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 28),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(
                      vertical: 30.0, horizontal: 40.0),
                  child: Column(
                    children: [
                      TextFormField(
                        onChanged: (value) {
                          name = value;
                          setState(() {});
                        },
                        style: TextStyle(fontSize: 20),
                        decoration: InputDecoration(
                            hintText: "Enter username", labelText: "username"),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return "Username cannot be empty";
                          }
                          return null;
                        },
                      ),
                      TextFormField(
                        style: TextStyle(fontSize: 20),
                        obscureText: true,
                        decoration: InputDecoration(
                            hintText: "Enter password", labelText: "password"),
                        validator: (value) {
                          if (value!.isEmpty) {
                            return "Password cannot be empty";
                          } else if (value.length < 6) {
                            return "Password length should be atleast 6";
                          }
                          return null;
                        },
                      ),
                      SizedBox(
                        height: 50.0,
                      ),
                      Material(
                        color: Colors.pinkAccent,
                        borderRadius: BorderRadius.circular(changebtn ? 60 : 8),
                        child: InkWell(
                          splashColor: Colors.yellow,
                          onTap: () => movetohome(context),
                          child: AnimatedContainer(
                            duration: Duration(seconds: 1),
                            width: changebtn ? 60 : 160,
                            height: 60,
                            // styling

                            alignment: Alignment.center,
                            child: changebtn
                                ? Icon(Icons.done)
                                : Text(
                                    "Login",
                                    style: TextStyle(
                                        fontSize: 25,
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold),
                                  ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
@smv8960
Copy link

smv8960 commented Jul 25, 2021

I matched your code with mine, they both are same, It ran on my system and worked well.
you should save the file and try to reopen on vscode and run the app,
it may work,
if not then you should create new project and paste all code in that project and try it there

@Divyesh3543
Copy link

i will make sure it will work
validator: (String? value) {
if (value == null || value.isEmpty) {
return "Please enter some text";
}
return null;
},

@Umar-Waseem
Copy link

Fixed the form validation issue, have a look at my code


import 'package:flutter/material.dart';
import 'routes.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool buttonChanged = false;
  String name = "";
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.grey[500],
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            const CircleAvatar(backgroundImage: AssetImage('images/login.jpg')),
            const SizedBox(height: 15.0),
            Text('Welcome $name',
                style: const TextStyle(
                    fontSize: 24.0, fontWeight: FontWeight.bold)),
            const SizedBox(height: 15.0),
            Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 15, vertical: 32),
                child: Column(
                  children: [
                    TextFormField(
                      decoration: const InputDecoration(
                          hintText: 'Enter the username',
                          labelText: 'UserName:'),
                      onChanged: (value) {
                        name = value;
                        setState(() {});
                      },
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter the username';
                        }
                        
                          return null;
                        
                        
                      },
                    ),
                    TextFormField(
                      obscureText: true,
                      decoration: const InputDecoration(
                          hintText: 'Enter the password',
                          labelText: 'Password:'),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return "Please enter password";
                        } else if (value.isNotEmpty && value.length < 6) {
                          return "Password must be at least 6 characters";
                        } else if (value.isNotEmpty && value.length > 12) {
                          return "Password must be less than 12 characters";
                        }

                        return null;
                      },
                    ),
                    const SizedBox(height: 15.0),
                    Material(
                        borderRadius:
                            BorderRadius.circular(buttonChanged ? 50.0 : 10.0),
                        color: Colors.blue,
                        child: InkWell(
                          splashColor: Colors.grey[7],
                          onTap: () => moveToHome(context),
                          child: AnimatedContainer(
                            duration: const Duration(seconds: 1),
                            width: buttonChanged ? 50 : 130,
                            height: 50,
                            alignment: Alignment.center,
                            child: buttonChanged
                                ? const Icon(Icons.done)
                                : const Text(
                                    'Login',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16),
                                  ),
                          ),
                        ))
                  ],
                ))
          ],
        ),
      ),
    );
  }

  moveToHome(BuildContext context) async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        buttonChanged = true;
        
      }
      );
      await Future.delayed(const Duration(seconds: 1));
      await Navigator.pushNamed(context, route.home);
      setState(() {
        buttonChanged = false;
      });
      
    }
    else{
      setState(() {
        buttonChanged = false;
      });
    }

  }
}


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants