You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法判断response.body是否为null?Flutter接口问题排查

问题

我尝试检查数据库中是否已存在指定用户名,使用了如下代码:

Future<bool> checkUsername(userName) async {
  try {
    final response = await http.post(
      Uri.parse('http://10.0.2.2:3000/username'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode({'user_name': userName}),
    );

    print('response ${response.body}'); // 此处打印结果为"response null"

    if (response.body.isEmpty || response.body == null) {
      print('eee here0');
      return false;
    } else if (json.decode(response.body)['user_id'] == userId) {
      print('eee here1');
      return false;
    } else {
      print('eee here2');
      return true;
    }
  } catch (e) {
    print('some error happenede checking username  $e');
    throw (e);
  }
}

但条件判断似乎不生效,出现了以下异常:

Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("user_id"))

即便print('response ${response.body}')的结果是response null,if语句也无法在抛出异常前捕获该情况!

分析与解决

问题根源

你打印的response null实际是字符串"null",而非Dart中的null对象。所以response.body == null判断不成立,同时"null".isEmpty返回false,导致第一个判断分支被跳过,直接进入json.decode(response.body)的逻辑。

对字符串"null"执行json.decode会得到Dart里的null,此时调用null['user_id']就会触发NoSuchMethodError异常。

修复代码

调整判断逻辑,处理字符串"null"的情况,同时优先检查请求状态码确保请求有效:

Future<bool> checkUsername(userName) async {
  try {
    final response = await http.post(
      Uri.parse('http://10.0.2.2:3000/username'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode({'user_name': userName}),
    );

    // 先验证请求是否成功
    if (response.statusCode != 200) {
      print('请求失败,状态码:${response.statusCode}');
      return false;
    }

    final body = response.body.trim();
    print('response $body');

    // 处理空字符串、字符串"null"的情况
    if (body.isEmpty || body == "null") {
      print('eee here0');
      return false;
    }

    // 包裹JSON解析逻辑,避免格式错误抛出异常
    try {
      final decoded = json.decode(body);
      // 确保解析结果是Map且包含user_id字段
      if (decoded is Map && decoded.containsKey('user_id') && decoded['user_id'] == userId) {
        print('eee here1');
        return false;
      }
    } catch (decodeError) {
      print('JSON解析失败:$decodeError');
      return false;
    }

    print('eee here2');
    return true;
  } catch (e) {
    print('检查用户名时出错:$e');
    rethrow;
  }
}

额外建议

  • 后端返回数据尽量保持格式统一,比如找不到用户时返回{"user_id": null}而非直接返回字符串"null",减少前端解析的异常情况。
  • 网络请求后优先检查响应状态码,能提前拦截请求失败的场景。

内容的提问来源于stack exchange,提问作者lovecode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:06:59