0

i have some problem with body in this code. at first there was only email and password,

login() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final response = await http.post(
  "https://api.batulimee.com//v1_ship/login_app",
  body:{
    "email": email,
    "password": password,
    "apikey": apikey,
  }),
);
final data = jsonDecode(response.body);
String status = data['status'];
String pesan = data['message'];
if (status == "success") {
  prefs.setString('stringValue', "apikey");
  Navigator.of(context).pushReplacement(PageRouteBuilder(
      pageBuilder: (_, __, ___) => new bottomNavBar(),
      transitionDuration: Duration(milliseconds: 600),
      transitionsBuilder:
          (_, Animation<double> animation, __, Widget child) {
        return Opacity(
          opacity: animation.value,
          child: child,
        );
      }));
  print(pesan);
  print(apikey);
} else {
  print(pesan);
}
}

and when i add apikey variable then try to login, i got an error like this.

Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null. Receiver: null Tried calling: length)

how should i put that apikey?

Aphron
  • 83
  • 1
  • 9
  • is "url" just a placeholder in the code snippet that u shared here. If url is a variable, please remove the quotes. – GunJack Oct 21 '20 at 07:04

1 Answers1

0

You should provide Map<String, String> as body for http.post. It might be possible that one or more of your values is not a string. Or that the "url" is not an actual url.

Use the jsonEncode() method on your body to make sure that it is string.

final response =
    await http.post("url", body: jsonEncode(<String, String> {
  "email": email,
  "password": password,
  "apikey": apikey,
 }),
);

Before you make the post request make sure that email, password and apikey are not null. Try printing them to console before making the request and make sure that these does not have null values.

Please take a look at docs Send Data to internet

Edit: I can't see how your login() method receives the values of email, password and apikey. In case these are the member of a class, which I am assuming, I would still check if they contain non-null values before sending a request. Your safe bet would be printing these to console just to check the contents of these variables.

debugPrint("Email: $email Pass: $password Key: $apikey"); 

Put this before your http.post() line and check if the values are null or not.

GunJack
  • 1,928
  • 2
  • 22
  • 35