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

Flutter中使用Prediction类型报未定义错误如何解决

问题背景

Flutter开发位置搜索功能时,编写位置查询业务逻辑时遇到Prediction类型无法识别的问题,相关实现代码如下:

lacemark _pickPlaceMark = Placemark();
Placemark get pickPlaceMark => _pickPlaceMark;
List<Prediction> _pridictionList = [];

Future<List<Prediction>> searchLocation(
    BuildContext context, String text) async {
  if (text != null && text.isNotEmpty) {
    http.Response response = await getLocationData(text);
    var data = jsonDecode(response.body.toString());
    print("Location is :" + data["status"]);
    if (data["status"] == "OK") {
      _pridictionList = [];
    }
  }
}

运行后抛出编译错误:

The name 'Prediction' isn't a type so it can't be used as a type argument. Try correcting the name to an existing type, or defining a type named 'Prediction'.
报错原因
  • Prediction不属于Flutter/Dart SDK内置类型,也不属于当前代码已导入依赖包的导出类型,编译器找不到该类型的定义,因此无法将其作为类型参数使用。通常该类是Google Places API地点联想接口返回结果对应的实体类,出现该报错说明你既未引入包含该类的相关依赖,也没有自定义实现对应数据模型。
  • 现有代码存在额外语法问题:首行Placemark类名拼写错误,写为了lacemark;searchLocation方法声明了Future<List<Prediction>>返回值,但方法内部没有对应返回语句,类型问题修复后仍会触发返回值缺失错误。
  • 现有业务逻辑不完整:接口请求成功后仅清空了预测结果列表,没有解析接口返回的地点数据填充列表,功能无法正常生效。
修复步骤
  • 解决Prediction类型缺失问题,二选一即可:
    • 若使用Google Places官方服务,引入对应Places功能依赖包,导入对应库后即可直接使用官方封装的Prediction类型。
    • 若自行封装接口请求,根据接口返回的JSON字段结构,自定义Prediction类,实现必要的字段定义和JSON转模型的序列化方法。
  • 修正拼写错误:将首行写错的lacemark改为Placemark。
  • 补全业务逻辑和返回值:接口请求成功后,遍历返回的联想地点数组,将每一项转换为Prediction实例存入列表,方法末尾返回列表结果匹配方法签名。

修复后的参考代码如下:

// 此处确保Prediction类型已通过依赖导入/自定义定义完成
Placemark _pickPlaceMark = Placemark();
Placemark get pickPlaceMark => _pickPlaceMark;
List<Prediction> _pridictionList = [];

Future<List<Prediction>> searchLocation(
    BuildContext context, String text) async {
  _pridictionList.clear();
  if (text.isNotEmpty) {
    final http.Response response = await getLocationData(text);
    final Map<String, dynamic> data = jsonDecode(response.body);
    print("Location request status: ${data["status"]}");
    if (data["status"] == "OK") {
      // 遍历接口返回的预测地点数据,转换为模型实例
      (data["predictions"] as List).forEach((item) {
        _pridictionList.add(Prediction.fromJson(item as Map<String, dynamic>));
      });
    }
  }
  return _pridictionList;
}

如果使用自定义Prediction类,需要为其实现fromJson命名构造函数,完成JSON数据到实体类的转换


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 22:24:11