skip to Main Content

I’m trying flutter and I’m newbie at this, I have a problem when I login with API SERVICE(im using Rest API https://reqres.in), the login says

_CastError (Null check operator used on a null value)

The error comes from source below

          Container(
              
              margin: const EdgeInsets.only(
                  left: 30, right: 30, top: 20, bottom: 20),
              padding: const EdgeInsets.symmetric(vertical: 10),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                 if (Loginvalues.loginFormKey.currentState!.validate()) {
                    Loginvalues.userLogin(Loginvalues.loginEmailController, Loginvalues.loginPasswordController,);
                 }
                },
                style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xff84c148),
                    elevation: 5,
                    padding: const EdgeInsets.all(15),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15))),
                child: const SizedBox(
                  height: 15,

                  child: Text('SIGN IN',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                        fontWeight: FontWeight.bold,
                      )),
                ),
              )),

At Line:

 onPressed: () {
   if (Loginvalues.loginFormKey.currentState!.validate()) { 
    Loginvalues.userLogin(Loginvalues.loginEmailController,  
    Loginvalues.loginPasswordController,);

This is my login controller dart where the loginFormkey was called:

// ignore_for_file: prefer_const_constructors

import 'dart:convert';
import 'package:get/get.dart';
import 'package:crud_sample/screens/home_page.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class LoginController with ChangeNotifier {
  TextEditingController loginEmailController = TextEditingController();
  TextEditingController loginPasswordController = TextEditingController();
  GlobalKey<FormState> loginFormKey = GlobalKey();

  userLogin(
    TextEditingController loginEmailController,
    TextEditingController loginPasswordController,
  ) async {
    try{
         var headers = {"Content-Type": "application/json"};
         var body = {
            'email' : loginEmailController.text.trim(),
            'password' : loginPasswordController.text.trim()
    };
    
       http.Response response = await http.post(
        Uri.parse('https://reqres.in/api/login'),
        headers: headers,
        body: jsonEncode(body),
        );
        
        if(response.statusCode == 200){
          Map json = jsonDecode(response.body.toString());
          print(json['token']);

          if(json['token'] != ''){
            Get.to(() => HomePage());
          }else{
            print("Invalid Details!");
          }
        }   
    }catch(e){
      print("Error $e");
    }
  }
}

My Dependencies

cupertino_icons: ^1.0.2
http: ^0.13.6
get: ^4.6.5
provider: ^6.0.5

Am I doing wrong?

Fix _CastError (Null check operator used on a null value)

2

Answers


  1. The error message suggests that you are using a null check operator (!) on a null value. In this case, it seems that Loginvalues.loginFormKey.currentState is null when you’re trying to access it.

    To fix this issue, you need to ensure that Loginvalues.loginFormKey.currentState is not null before using the null check operator. You can modify your code as follows:

    onPressed: () {
      if (Loginvalues.loginFormKey.currentState != null &&
          Loginvalues.loginFormKey.currentState!.validate()) {
        Loginvalues.userLogin(
          Loginvalues.loginEmailController,
          Loginvalues.loginPasswordController,
        );
      }
    },
    

    By adding the null check Loginvalues.loginFormKey.currentState != null before accessing validate(), you can prevent the null check operator from being used on a null value.

    Make sure to update this change in your code and try running it again.

    I hope this helps you resolve the issue!

    Login or Signup to reply.
  2. if (Loginvalues.loginFormKey.currentState != null &&) {
       if(Loginvalues.loginFormKey.currentState!.validate()){
        Loginvalues.userLogin(
          Loginvalues.loginEmailController,
          Loginvalues.loginPasswordController
        );
      }
      }
    

    Change the following part with this. As it is giving error. Here you will first check if it is null. if not only then meet the condition and fulfill it. Hope this helps.

    Edit:

    if (Loginvalues.loginFormKey.currentState != null &&) {
       if(Loginvalues.loginFormKey.currentState!.validate()){
          Loginvalues.userLogin(
            Loginvalues.loginEmailController,
            Loginvalues.loginPasswordController,context
          );
        }
      }
    

    Here send context with it. And on the other part:

    if(json['token'] != ''){
            Navigator.push(
            context,
           MaterialPageRoute(builder: (context) => HomePage()),
       );
            }else{
             print("Invalid Details!");
           }
    

    Receive the context.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search