Home > Back-end >  how to make validation form in flutter with null safety
how to make validation form in flutter with null safety

Time:02-15

how to make validation form in flutter with null safety, there is a problem, but I can't select in formkey or filed and I try alot of ways, you can see this code and try to help me to use null safty, thank

I have the following code to class

import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:login_project/shared/components/components.dart';
    
    class LoginScreen extends StatefulWidget{
      @override
      _LoginScreenState createState() => _LoginScreenState();
    }
    
    class _LoginScreenState extends State<LoginScreen> {
      var emailController= TextEditingController();
    
      var passwordController= TextEditingController();
    
      var formKey = GlobalKey<FormState>();

I use form key to put it in Form Widget becuse the TFF in form widget then I use validator

 validator:(String? value){
                        if(value != null && value.isEmpty){
                          return "password must be not empty";
                        }
                          return null;
                      },

then in button I hava this :

 defaultButton(
                        // width:double.infinity,
                      text: 'Login',
                        // background: Colors.blue,
                      function: (){
    
                        if(formKey.currentState!.validate()){
                          print(emailController.text);
                          print(passwordController.text);
                        }
    
                      },
      

but I hava error in null saftey in TTF or formKey and I try to solve it then make a screen as null check operator. Thanks

CodePudding user response:

Please use it:

validator:(String? value){
  if(value!.isEmpty){
    return "password must be not empty";
  }
  return null;
},

CodePudding user response:

make code like this :

validator:(String? value){
  if(value!.isEmpty){
    return "password must be not empty";
  }
  return null;
},

and delete custom button and put it :

 child: MaterialButton(
                onPressed:(){
                  if(_formKey.currentState!.validate()){
                        print(emailController.text);
                        print(passwordController.text);
                      }
              },
  • Related