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

Flutter中如何检测HTTP请求的响应是否为Null

如何检测Dart http请求的响应是否为Null?

我在使用http包时,想检测HTTP请求的响应是否为Null(比如输入错误URL的情况),在DartPad里测试了如下代码:

import 'dart:convert' as convert;

import 'package:http/http.dart' as http;

void main(List<String> arguments) async {
  // This example uses the Google Books API to search for books about http.
  // https://developers.google.com/books/docs/overview
  var url =
      Uri.https('www.googl', '/books/v1/volumes', {'q': '{http}'});

  // Await the http get response, then decode the json-formatted response.
  var response ;
  try{
       response = await http.get(url);
  }
  on Exception catch (_) {
  print(response.toString().isEmpty); 
  print(response.statusCode.toString());  
  print(response.body.isNotEmpty);
  print(response.headers.isEmpty);
  }
   if (response.statusCode == 200) {
    var jsonResponse =
        convert.jsonDecode(response.body) as Map<String, dynamic>;
    var itemCount = jsonResponse['totalItems'];
    print('Number of books about http: $itemCount.');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

运行后得到如下输出:

false
Uncaught Error: NoSuchMethodError: method not found: 'get$body' on null

此时response.toString()并非NULL,请问该如何检测响应是否为Null?


解决方案

你的核心问题是:当请求抛出异常时,response并未被赋值,仍为Null,但你直接调用了它的属性/方法,导致报错。正确的检测方式是直接通过response == null判断,而非调用它的toString方法。

修正后的代码示例:

import 'dart:convert' as convert;

import 'package:http/http.dart' as http;

void main(List<String> arguments) async {
  var url = Uri.https('www.googl', '/books/v1/volumes', {'q': '{http}'});

  var response;
  try {
    response = await http.get(url);
  } on Exception catch (_) {
    // 直接判断响应是否为Null
    if (response == null) {
      print('请求失败,无有效响应');
      return; // 终止后续代码执行,避免空指针
    }
  }

  // 先确认响应非Null,再处理业务逻辑
  if (response != null) {
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body) as Map<String, dynamic>;
      var itemCount = jsonResponse['totalItems'];
      print('关于HTTP的书籍数量:$itemCount.');
    } else {
      print('请求失败,状态码:${response.statusCode}.');
    }
  } else {
    print('请求未获取到响应');
  }
}

关键说明

  • 当请求因域名错误、网络问题等抛出异常时,await http.get(url)不会返回值,response保持初始的Null状态。
  • 永远不要在未确认response非Null的情况下,调用它的statusCode、body等属性,否则会触发NoSuchMethodError。
  • 检测Null的正确方式是直接使用response == null,这是Dart中判断空值的标准写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:18:32