Generics 未处理的异常:类型';(T) =>;字符串';不是类型为';(对象)=>;字符串';

Generics 未处理的异常:类型';(T) =>;字符串';不是类型为';(对象)=>;字符串';,generics,dart,Generics,Dart,我有一个意想不到的错误。以下是在标题中产生错误的简化代码: typedef ItemView<T> = String Function(T); class Item { final String title; Item(this.title); } class Field<T, A> { final T value; final A attributes; Field(this.attributes, this.value); } class

我有一个意想不到的错误。以下是在标题中产生错误的简化代码:

typedef ItemView<T> = String Function(T);

class Item {
  final String title;

  Item(this.title);
}

class Field<T, A> {
  final T value;
  final A attributes;

  Field(this.attributes, this.value);
}

class Attributes<T> {
  final List<T> items;
  final ItemView<T> itemToString;

  Attributes(this.items, this.itemToString);
}

void main() {
  final fields = [createField<Item>(
      [Item("Value 1"), Item("Value 2")], (item) => item.title)];

  if (fields[0] is Field<Object, Attributes<Object>>) {
    final field = fields[0] as Field<Object, Attributes<Object>>;
    final a = field.attributes;

    String text = a.itemToString(a.items[0]); // Unhandled Exception: type '(Item) => String' is not a subtype of type '(Object) => String'
    print(text); 
  }
}

Field<Object, Object> createField<T>(List<T> items, ItemView<T> itemToString) {
  final attributes = Attributes<T>(items, itemToString);
  final field = Field<T, Attributes<T>>(attributes, null);
  return field;
}
typedef ItemView=字符串函数(T);
类项目{
最后的字符串标题;
项目(本标题);
}
类字段{
最终T值;
最终A属性;
字段(this.attributes,this.value);
}
类属性{
最后清单项目;
最终项目视图项目字符串;
属性(this.items、this.itemToString);
}
void main(){
最终字段=[createField](
[项目(“价值1”)、项目(“价值2”),(项目)=>项目名称];
如果(字段[0]是字段){
最终字段=字段[0]作为字段;
最终a=字段属性;
String text=a.itemToString(a.items[0]);//未处理的异常:type'(Item)=>String'不是type'(Object)=>String'的子类型
印刷品(文本);
}
}
字段createField(列表项、ItemView项到字符串){
最终属性=属性(项目、项目字符串);
最终字段=字段(属性,空);
返回字段;
}
这段代码会抛出一个错误,但我希望看到一条“Value 1”消息。 与代码抗争有一段时间,我发现如果我将代码更改为这样一点:

class Attributes<T> {
  final List<T> items;
  final ItemView<T> _itemToString;

  Attributes(this.items, this._itemToString);

  String itemToString(T value) {
    return _itemToString(value);
  }
}
类属性{
最后清单项目;
最终项目视图_itemToString;
属性(this.items,this.\u itemToString);
字符串itemToString(T值){
返回_itemToString(值);
}
}

它会像我预期的那样工作。所以问题是:为什么第一个变体不起作用?这是一种预期的行为吗?还是某种虫子?第一个代码和第二个代码之间有什么显著的区别,从而使代码有效?

我认为这是
dart
类型推断
被混淆的情况之一。是的,我也这样认为。我认为这是
dart
类型推断
变得混乱的情况之一。是的,我也这样认为。