Flutter模型类报错:'Null'不是'String'的子类型求助
问题分析
错误'Null' is not a subtype of type 'String'的核心原因有两个:
- Google Place Autocomplete API返回的部分字段为null,但模型类直接将null赋值给了非空的String变量;
- API请求URL存在语法错误,可能导致返回异常数据。
修复步骤
1. 修正API请求的两处错误
- 纬度和经度的分隔符错误:把
%改成逗号,; - 经度取值错误:将
current_pos.latitude改为current_pos.longitude。
修正后的请求URL代码:
void find_location(String placeName, Position current_pos) async { if (placeName.isNotEmpty) { // 用isNotEmpty替代!=null,判断更严谨 final current_lat = current_pos.latitude; final current_lon = current_pos.longitude; // 修正经度取值 String auto_complete_url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$placeName&key=$google_map_api_key&components=country:pk&radius=100000&location=$current_lat,$current_lon"; // 后续代码保持不变 } }
2. 修复模型类的空值处理
Google Places API的secondary_text属于structured_formatting子节点,你之前直接从根节点取值是错误的,同时要对所有字段做空值兜底:
// ignore_for_file: non_constant_identifier_names class PlacePredictions { // 类名首字母大写,符合Dart规范 String secondaryText = ""; String mainText = ""; String placeId = ""; PlacePredictions({ required this.secondaryText, required this.mainText, required this.placeId, }); PlacePredictions.fromJson(Map<String, dynamic> json) { // 用??运算符给null值设置默认空字符串 placeId = json["place_id"] ?? ""; // 先判断structured_formatting是否存在,再取子字段 mainText = json["structured_formatting"]?["main_text"] ?? ""; secondaryText = json["structured_formatting"]?["secondary_text"] ?? ""; } }
如果允许字段为空,也可以使用可空类型(但后续UI层需要处理空值):
class PlacePredictions { String? secondaryText; String? mainText; String? placeId; PlacePredictions({ required this.secondaryText, required this.mainText, required this.placeId, }); PlacePredictions.fromJson(Map<String, dynamic> json) { placeId = json["place_id"]; mainText = json["structured_formatting"]?["main_text"]; secondaryText = json["structured_formatting"]?["secondary_text"]; } }
3. 简化状态更新逻辑
去掉冗余的变量赋值,直接在setState中更新列表:
if (response["status"] == "OK") { var predictions = response["predictions"]; var place_lst = (predictions as List).map((e) => PlacePredictions.fromJson(e)).toList(); setState(() { placePredictions_lst = place_lst; }); }
关键注意事项
- 必须对API返回的所有字段做空值校验,即使
status为OK,部分字段仍可能为空; - 严格按照Google Places API的返回结构取值,
secondary_text和main_text都在structured_formatting节点下; - Dart空安全要求必须处理null值,要么给默认值,要么使用可空类型。
内容的提问来源于stack exchange,提问作者Ronit Kataria
相关产品推荐
相关产品推荐

