未处理的异常:类型'(T)=>字符串'不是类型'(Object)=>字符串'的子类型

时间:2020-06-25 12:53:35

标签: 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 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;
}

此代码引发错误,但是我期望出现“值1”消息。 一段时间以来,我一直在努力处理代码,我想出了如果我对代码进行如下更改的话:

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

  Attributes(this.items, this._itemToString);

  String itemToString(T value) {
    return _itemToString(value);
  }
}

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

0 个答案:

没有答案