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

Flutter类型报错:Country类型未定义[]操作符的解决方法

解决"The operator '[]' isn't defined for the type of 'Country'"错误

问题根源

你犯了两个关键的类型错误:

  1. 直接把API返回的List<Map<String, dynamic>>赋值给List<Country>,没有完成类型转换
  2. 用Map的[]操作符访问自定义Country类的属性,而非类的成员访问语法.

分步解决

1. 给Country类添加fromJson构造函数

需要把API返回的Map对象转换成Country实例,给类新增一个工厂构造函数:

class Country {
  final int id;
  final String createdAt;
  final String updatedAt;
  final String name;

  const Country({
    required this.id,
    required this.createdAt,
    required this.updatedAt,
    required this.name
  });

  // 添加该构造函数,实现Map到Country对象的转换
  factory Country.fromJson(Map<String, dynamic> json) {
    return Country(
      id: json['id'] as int,
      createdAt: json['createdAt'] as String,
      updatedAt: json['updatedAt'] as String,
      name: json['name'] as String,
    );
  }
}

2. 修正getCountries方法的类型转换逻辑

将API返回的response['list']中的每个Map都转换成Country实例:

Future<void> getCountries() async {
  try {
    final response = await _apiService.getCountries();
    // 把List<Map>转换为List<Country>
    countries = (response['list'] as List)
        .map((item) => Country.fromJson(item as Map<String, dynamic>))
        .toList();
  } catch (e) {
    log(e.toString());
    rethrow;
  }
}

3. 修正属性访问代码

用.访问Country类的成员变量,替代[]操作符:

// 正确的map转换写法
final List<String> countriesWithNames = countries.map((country) => country.name).toList();

// 按索引访问属性的正确写法
String countryName = countries[index].name;

这样就能彻底解决类型错误问题,既保证类型安全,又能正常访问数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:35:32