【问题标题】:(NoSuchMethodError: The getter 'length' was called on null. Receiver: null Tried calling: length) [duplicate](NoSuchMethodError:在 null 上调用了 getter 'length'。接收方:null 尝试调用:length)[重复]
【发布时间】:2020-10-21 06:56:39
【问题描述】:

我在这段代码中遇到了一些问题。一开始只有邮箱和密码,

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?

【问题讨论】:

  • 是“url”只是您在此处共享的代码 sn-p 中的占位符。如果 url 是变量,请去掉引号。

标签: api flutter dart


【解决方案1】:

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

在你的 body 上使用jsonEncode() 方法来确保它是字符串。

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

在发出发布请求之前,请确保 email、password 和 apikey 不为空。在发出请求之前尝试将它们打印到控制台,并确保它们没有空值。

请查看文档Send Data to internet

编辑:我看不到您的login() 方法如何接收email、password 和apikey 的值。如果这些是我假设的类的成员,我仍然会在发送请求之前检查它们是否包含非空值。您可以放心地将这些打印到控制台以检查这些变量的内容。

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

把它放在http.post() 行之前,检查值是否为空。

【讨论】:

  • 对不起,我将编辑我的代码并重新发送,请看一下
猜你喜欢
  • 2018-12-03
  • 2020-06-15
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多