(NoSuchMethodError:对null调用了getter'length'。Receiver:null尝试调用:length)

时间:2020-10-21 06:56:39

标签: api flutter dart

我在这段代码中的身体有些问题。一开始只有电子邮件和密码,

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);
}
}

当我添加apikey变量然后尝试登录时,出现了这样的错误。

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

我应该如何放置那个apikey?

1 个答案:

答案 0 :(得分:0)

您应提供Map<String, String>作为http.post的正文。您的一个或多个值可能不是字符串。或者"url"不是实际的网址。

在您的身体上使用jsonEncode()方法以确保它是字符串。

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

在发出发布请求之前,请确保emailpasswordapikey不为空。发出请求之前,请尝试将它们打印到控制台,并确保它们不具有空值。

请查看文档Send Data to internet

编辑:我看不到您的login()方法如何接收emailpasswordapikey的值。如果我假设这些是类的成员,我仍然会在发送请求之前检查它们是否包含非null值。您最好的选择是将它们打印到控制台,以检查这些变量的内容。

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

将其放在您的http.post()行之前,并检查值是否为空。