简体   繁体   中英

how to make validation form in flutter with null safety

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

Please use it:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM