首页 > 解决方案 > Flutter - The method '[]' was called on null

问题描述

I' just retreiving the profile information from the server, i ain't creating any model I'm directly updating the values but while fetching the data I'm getting an error as Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.

This is my json response

{
    "status": true,
    "record": {
        "user_id": "20",
        "user_name": null,
        "user_phone": null,
        "user_email": null
    }
}

And this is how i'm fetching from server and saving it.

 String userId = "";
 final response = await http.post(profileUrl, headers: headers, body: body);
    if(response.statusCode == 200){
      print('Response in Profile Screen: ' + response.body);
      setState(() {
        username = jsonResponse['record']['user_id];
        print(username + "Userid");
      });
    }

And when I'm trying to print the userId i'm getting the error

标签: jsonflutterdart

解决方案


您应该先将response.body分配给jsonResponse

  var jsonResponse = response.body;
  jsonResponse['record']['user_id'];

推荐阅读