Dart 将类传递给函数

Dart 将类传递给函数,dart,Dart,我想将类User作为第二个参数传递给load-函数 也许有人知道怎么做 class App { Map<String, List<Model>> models = { 'users': List<User>() }; App() { load('users'); } void load(resource) { Directory directory = Directory.fromUri(Uri(path: '.

我想将类
User
作为第二个参数传递给
load
-函数

也许有人知道怎么做

class App {
  Map<String, List<Model>> models = {
    'users': List<User>()
  };

  App() {
    load('users');
  }

  void load(resource) {
    Directory directory = Directory.fromUri(Uri(path: './app/data/' + resource));
    for (FileSystemEntity file in directory.listSync(recursive: false)) {
      Map<String, dynamic> fileContent = jsonDecode(File(file.uri.path).readAsStringSync());
      models[resource].add(User.fromJson(fileContent));
    }
  }
}
class应用程序{
地图模型={
“用户”:列表()
};
App(){
加载(“用户”);
}
无效负载(资源){
Directory=Directory.fromUri(Uri(路径:'./app/data/'+resource));
for(directory.listSync中的FileSystemEntity文件(递归:false)){
Map fileContent=jsonDecode(文件(File.uri.path).readAsStringSync());
模型[resource].add(User.fromJson(fileContent));
}
}
}
你不能。 您可以将
Type
对象作为参数传递,也可以将Type作为类型参数传递(
load(resource){…}
),但这两种方法都不允许您对类型调用
User.fromJson

您可以做的是将
User.fromJson
函数作为参数传递(或者,如果是构造函数,则将
(x)=>User.fromJson(x)
作为参数传递)。即:

void加载(字符串资源,对象?fromJson(映射json)){
... 
map[resoruce].add(fromJson(fileContent));
}
然后

load(“someName”,(map)=>User.fromJson(map));