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

Flutter类型转换错误求助:'String'非'Movie'/'int'子类型

错误排查与修复方案

错误1:type 'String' is not a subtype of type 'int' of 'index'

问题根源

第96行的data[Index]存在两处问题:

  • Index未加引号,会被当作变量而非Firestore文档的字段名,若实际要取的字段是index(字符串类型的键),必须写成data['index']。
  • 用?? ""设置了字符串默认值,但index字段应为整数类型,类型不匹配直接触发转换错误。

修复代码

将字段引用和默认值修正为:

int index = data['index'] ?? 0;

错误2:type 'String' is not a subtype of type 'Movie'

问题根源

MovieItem组件要求接收Movie类型的参数,但当前传入的是data[Index] ?? ""(字符串或错误类型的值),未从Firestore返回的Map数据中正确构建Movie对象。

修复步骤

  1. 确保Movie类包含从Map生成实例的构造函数(比如fromMap):
class Movie {
  final int index;
  // 补充你的其他字段

  Movie({required this.index, /* 其他必填参数 */});

  factory Movie.fromMap(Map<String, dynamic> map) {
    return Movie(
      index: map['index'] ?? 0,
      // 映射其他字段到类属性
    );
  }
}
  1. 修正第96行的MovieItem调用,传入正确的Movie实例:
return MovieItem(Movie.fromMap(data));

完整修正后的关键代码片段

return ListView(
  children: snapshot.data!.docs.map(
    (DocumentSnapshot document) {
      Map<String, dynamic>? data =
          document.data() as Map<String, dynamic>;

      // 修正后的调用逻辑
      return MovieItem(Movie.fromMap(data));
    },
  ).toList(),
);

内容的提问来源于stack exchange,提问作者ISLAM IS LIFE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:55:34