NoSuchMethodError: The getter 'status' was called on null on flutter

Viewed 721

I want to showing json like this from flutter

{"status":true,"message":"Successfully Login!","acc_id":"2","email":"cikananda2020@gmail.com","password":"9a365b0597e198ceac41966db1d6f47de66a86bb99e3e5a811c3030"}

but when i click login from flutter, i got this result

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The getter 'status' was called on null.

Here is my login function

void login() async {
    UserResults userResults;
    await UserResults.sqlLogin(
            email: email, password: password,url: BaseURL.kLoginUrl)
        .then((value) => userResults = value as UserResults);
    print(userResults.status);
    if (userResults.status == true) //error start here {
      SharedPref.simpanPrefereneces(
          userResults.email);
      Navigator.pushReplacementNamed(context, HomeScreen.id);
      print(userResults.message);
    } else {
      _scaffoldKey.currentState.showSnackBar(SnackBar(
        content: Text(userResults.message),
        duration: Duration(seconds: 3),
      ));
    }
  }

and here is my SqlLogin

  static Future<UserResults> sqlLogin(
      {String email, String password, String idUser, String url}) async  {
    var url = "http://192.168.0.23/Api/login.php?email=" + email + "&password=" + password;
    final response = await http.get(url,headers:{"Content-Type":
    "application/json"});
    Map<String, dynamic> data = new Map<String, dynamic>.from(json.decode(response.body));

    print(data['email']);
    print(data['password']);
    print(data['acc_id']);
    print(data['status']);

  }

}

here is my console log

I/flutter ( 7370): cikananda2020@gmail.com
I/flutter ( 7370): 9a365b0597e198ceac41966db1d6f47de66a86bb99e3e5a811c3030
I/flutter ( 7370): 2
I/flutter ( 7370): true
E/flutter ( 7370): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The getter 'status' was called on null.
E/flutter ( 7370): Receiver: null
E/flutter ( 7370): Tried calling: status

What's happening to my code? is something wrong about status part or any suggestion for this? Because my API is working properly. thank you

1 Answers

status is null because you didn't return data in sqlLogin. Since you want to convert data as UserResults, you dont need to convert them as Map.

static Future<UserResults> sqlLogin({String email, String password, String idUser, String url}) async  {
    var url = "http://192.168.0.23/Api/login.php?email=" + email + "&password=" + password;
    final response = await http.get(url,headers:{"Content-Type":
    "application/json"});
     var res = UserResults.fromJson(json.decode(response.body));
     return res; 
}
Related