Home > Blockchain >  _CastError (Null check operator used on a null value) flutter
_CastError (Null check operator used on a null value) flutter

Time:04-01

_CastError (Null check operator used on a null value)

error code

bool validateAndSave() {
    final form = globalFormKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    }
    return false;
  }

full code

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:thex/components/account_check.dart';
import 'package:thex/components/rounded_button.dart';
import 'package:thex/components/rounded_input_field.dart';
import 'package:thex/components/rounded_password_field.dart';
import 'package:thex/constants.dart';
import 'package:thex/models/login_model.dart';
import 'package:thex/screen/Login/components/background.dart';
// import 'package:thex/screen/home/home_screen.dart';
import 'package:thex/screen/signup/signup_screen.dart';
import 'package:url_launcher/url_launcher.dart';


class Body extends StatelessWidget {
   Body({
    Key? key,
  }) : super(key: key);

  final scaffoldKey = GlobalKey<ScaffoldState>();
  GlobalKey<FormState> globalFormKey = GlobalKey<FormState>();
  LoginRequestModel? requestModel;

  void initState() {
    requestModel = LoginRequestModel();
  }
  

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Background(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: size.height * 0.04),
            child: const Text(
              "Sign In", 
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 34, color: kPrimaryColor),
            ),
          ),
          SvgPicture.asset(
            "assets/icons/login.svg", 
            height: size.height * 0.35
          ),
          RoundedInputField(
            validator: (value) => ! value!.contains('@') ? null : 'Invalid Email',
            hintText: "Your Email",
            onSaved: (value) {
              requestModel!.email = value;
            },
          ),
          RoundedPasswordField(
            validator: (password) =>  password!.length < 6 ? 'Password too short' : null,
            hintText: "Your Password",
            onSaved: (password) {
              requestModel!.password = password;
            },
          ),
          RoundedButton(
            text: "LOGIN",
            press: () {
              if (validateAndSave()) {
                print(requestModel!.toJson());
              }
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(
              //     builder: (context) {
              //       return const HomeScreen();
              //     },
              //   ),
              // );
            
            },
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              AlreadyHaveAnAccountCheck(
                press: () {
                  Navigator.push(
                    context, 
                    MaterialPageRoute(
                      builder: (context){
                        return const SignUpScreen();
                      },
                    ),
                  );
                },
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text("Don't have an account? ", style: TextStyle(color: kPrimaryColor),),
              GestureDetector(
                onTap: () { launch("https://www.web.com/forgot-password");},
                child: const Text("Reset Password", style: TextStyle(color: kPrimaryColor),),
              ),
            ],
          )
        ],
      ),
    );
  }  

  bool validateAndSave() {
    final form = globalFormKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    }
    return false;
  }
}

help!!

CodePudding user response:

You shouldn't use "!" to force not null. Instead, use ?? defaultValue or check null before use "!". Also, use debugging mode (f5) to check flow and know where code die.

CodePudding user response:

I've changed like this, but there is no response in the console. there should be a print requestModel

bool validateAndSave() {
        final form = globalFormKey.currentState;
        if (form?.validate != null) {
          form!.save();
          return true;
        } else {
          return false;
        }
      }

CodePudding user response:

Problem is you dont have a form element in your widget. There for its null.

You need to add a Form widget with the key.

@override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Background(
      child: Form(
         key: globalFormKey,
         child: Column(
            ...
         )
      )
   );
} 
  • Related