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

Flutter泛型报错:'(Brand)=>int'不是'((dynamic)=>Comparable<dynamic>)?'的子类型

解决Dart泛型函数传递的类型不匹配错误

错误信息

_TypeError (type '(Brand) => int' is not a subtype of type '((dynamic) => Comparable<dynamic>)?')

问题根源

代码中存在泛型类型不兼容问题:

  • DataColumnsSorter<Brand, num>的onSort是Comparable<num> Function(Brand)类型
  • _sort方法的参数getField定义为Comparable Function(dynamic d),Dart函数类型是逆变的,具体类型的函数无法直接赋值给动态参数的函数类型,导致类型转换失败。

解决方案

让整个调用链的泛型类型保持一致:将_sort改为泛型方法,接收具体的模型类型T,同时确保paginationData的sort方法对应相同泛型类型,这样就能完美匹配DataColumnsSorter的泛型函数类型。

修正后的代码

1. 泛型类(保持不变)

class DataColumnsSorter<T, R> {
  DataColumnsSorter({
    required this.isNumeric,
    required this.type,
    required this.columnName,
    required this.onSort,
  });
  bool isNumeric;
  dynamic type;
  String columnName;
  Comparable<R> Function(T)? onSort;
}

2. 实例化对象(保持不变)

final sorter = DataColumnsSorter<Brand, num>(
  columnName: 'id',
  isNumeric: true,
  onSort: (brand) => brand.id ?? 0,
  type: 0,
);

3. 修正_sort为泛型方法

/// 创建PaginatedDataTable的列
DataColumn(
  label: Text(sorter.columnName),
  numeric: sorter.isNumeric,
  onSort: (colIndex, asc) {
    // 传递具体的Brand类型给泛型方法
    _sort<Brand>(sorter.onSort!, colIndex, asc, paginationData, bloc);
  },
);

// 改为泛型方法,接收模型类型T
void _sort<T>(
  Comparable Function(T d) getField,
  int colIndex,
  bool asc,
  BlocPaginationData<T> paginationData, // 指定泛型T
  BlocDataTableCubit bloc,
) {
  paginationData.sort(getField, asc);
  bloc.setAsc = asc;
  bloc.setSortColumnIndex = colIndex;
}

4. 确保BlocPaginationData的泛型定义

// 明确泛型T的定义
class BlocPaginationData<T> extends DataTableSource {
  // ... 其他代码 ...

  void sort(Comparable Function(T d) getField, bool asc) {
    bloc.data.sort((a, b) {
      final aValue = getField(a);
      final bValue = getField(b);
      return asc
          ? Comparable.compare(aValue, bValue)
          : Comparable.compare(bValue, aValue);
    });
    notifyListeners();
  }
}

核心说明

  • 泛型方法_sort<T>让函数参数getField的类型与DataColumnsSorter<T, R>的onSort完全匹配,避免了动态类型转换的风险
  • BlocPaginationData明确泛型T后,sort方法的参数类型与上游保持一致,彻底解决类型不兼容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:47:11