dart 泛型定义求教

#1

先贴上代码

typedef bool Build<T>(T a); 
typedef T FetchData<T>(); 

bool buidDataFromList(List<Map<String, String>> data) {
  print(data.length);
  return true;
}

List<Map<String, String>> fetchPostAsList() {
  return [
    {"title": "post1", "url": "http://www.baidu.com"}
  ];
}

void main() {
  var instance = new Aclass(
    callback: buidDataFromList,
    fetchData: fetchPostAsList
  );
  instance.test();
}

class Aclass {
  final Build callback;
  final FetchData fetchData;

  Aclass({this.fetchData, this.callback});

  test() {
    this.callback(this.fetchData());
  }
}

以上代码执行报错

dio.dart:1: Warning: Interpreting this as package URI, 'package:flutter_forum/dio.dart'.
dio.dart:17:15: Error: The top level function has type 'bool Function(List<Map<String, String>>)' that isn't of expected type 'bool Function(dynamic)'.
 - 'List' is from 'dart:core'.
 - 'Map' is from 'dart:core'.
Change the type of the function or the context in which it is used.
    callback: buidDataFromList,

如果把buidDataFromList的定义修改成如下,则能运行成功

bool buidDataFromList(data) {
  print(data.length);
  return true;
}

但是这种方式导致在写代码的时候,ide无法识别buidDataFromList函数里data的类型,导致代码提示无效。求教正确的定义方式应该是怎样的

#2

Build 没有添加类型参数,应该是 final Build<List<Map<String, String>>> callback;

1赞
#3

Aclass这个类的初衷是为了定义不同类型的获取数据以及解析方法,你这样修改就限制了输入参数的类型。
受你的启发,把参数也定义成泛型,就可以了。
多谢指导!

class Aclass<T> {
  final Build<T> callback;
  final FetchData fetchData;

  Aclass({this.fetchData, this.callback});

  test() {
    this.callback(this.fetchData());
  }
}
#4

stackoverflow上有个和我类似的问题,记录一下