Flutter异步接口请求函数非空类型报错求解
问题原因
报错的核心是Dart非空安全规则:你的函数返回类型是Future<List<AllProductModel>>(非空),但当API返回"Data not found"时,else分支没有返回任何符合类型的值,编译器认为函数可能返回null,触发报错。
解决方案
根据业务场景,有三种可行的修改方式:
1. 返回空列表(推荐用于无数据属于正常情况)
当"Data not found"是正常业务状态(比如用户还未发布任何产品),直接返回空列表,确保所有代码路径都返回符合类型的值:
Future<List<AllProductModel>> fetchYourProduct(Uid) async { final url = 'https://*****************.php?UserPost=' + Uid.toString(); final response = await http.get(Uri.parse(url)); final body = json.decode(response.body); // 复用已解码的body,避免重复调用json.decode if (body != "Data not found") { return body.map<AllProductModel>(AllProductModel.fromJson).toList(); } else { return []; // 返回空列表,满足非空返回类型要求 } }
2. 抛出异常(推荐用于无数据属于错误情况)
如果"Data not found"是异常场景(比如请求的用户ID无效),可以抛出异常,由上层调用时通过try-catch处理:
Future<List<AllProductModel>> fetchYourProduct(Uid) async { final url = 'https://*****************.php?UserPost=' + Uid.toString(); final response = await http.get(Uri.parse(url)); final body = json.decode(response.body); if (body != "Data not found") { return body.map<AllProductModel>(AllProductModel.fromJson).toList(); } else { throw Exception("未找到对应数据"); // 抛出异常,终止函数并传递错误信息 } }
3. 修改返回类型为可空(不推荐,增加上层处理成本)
允许函数返回null,但需要将返回类型改为Future<List<AllProductModel>?>,上层调用时必须处理null的情况:
Future<List<AllProductModel>?> fetchYourProduct(Uid) async { final url = 'https://*****************.php?UserPost=' + Uid.toString(); final response = await http.get(Uri.parse(url)); final body = json.decode(response.body); if (body != "Data not found") { return body.map<AllProductModel>(AllProductModel.fromJson).toList(); } else { return null; // 返回null,需配合可空返回类型 } }
内容的提问来源于stack exchange,提问作者M Al
相关产品推荐
相关产品推荐

