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

Flutter GetX API联调报错:fetchProducts方法非空返回问题求助

解决Flutter GetX API服务类非空类型报错

问题原因

你的fetchProducts函数声明返回Future<ProductModel>(非可空类型),但仅在HTTP响应状态码为200时返回有效数据。如果请求失败(比如状态码不是200),函数没有任何返回值,Dart空安全机制会触发报错——此时函数可能隐式返回null,与声明的非可空返回类型冲突。

解决方案

针对这个问题,有两种常见处理方式:

方式1:抛出异常处理错误

在非200状态码时抛出异常,明确告知请求失败,调用方可以通过try-catch捕获并处理错误:

import 'package:http/http.dart' as http;
import 'package:practice/productmodule/models/product_model.dart';
import 'package:get/get.dart';

class ApiService {
  static var client = http.Client();
  static Future<ProductModel> fetchProducts() async {
    var response = await client.get(Uri.parse('https://....../1'));
    if (response.statusCode == 200) {
      var jsonString = response.body;
      return productModelFromJson(jsonString);
    } else {
      // 抛出带状态码的异常
      throw Exception('加载商品失败,状态码:${response.statusCode}');
    }
  }
}

方式2:改为返回可空类型

将返回类型改为Future<ProductModel?>,非200状态时返回null,调用方需判断结果是否为null:

import 'package:http/http.dart' as http;
import 'package:practice/productmodule/models/product_model.dart';
import 'package:get/get.dart';

class ApiService {
  static var client = http.Client();
  static Future<ProductModel?> fetchProducts() async {
    var response = await client.get(Uri.parse('https://....../1'));
    if (response.statusCode == 200) {
      var jsonString = response.body;
      return productModelFromJson(jsonString);
    }
    // 非200状态返回null
    return null;
  }
}

选择建议

  • 若请求失败属于异常场景(比如必须获取数据才能继续),优先用方式1,通过异常捕获统一处理错误逻辑。
  • 若允许无数据的情况(比如网络波动时显示空状态),可以用方式2,在UI层判断null后展示对应界面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:52:43