在Dart中将类静态工厂作为方法参数传递 [英] Passing class static factory as method parameter in Dart

查看:56
本文介绍了在Dart中将类静态工厂作为方法参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用泛型来抽象发出不同的HTTP请求.我正在使用 json_serializale 生成 fromJson() toJson()方法.

I'm currently attempting to abstract making different HTTP requests by using generics. I'm using json_serializale for generating fromJson() and toJson() methods.

这是一个简单的模型文件:

Here is a simple model file:

import 'package:json_annotation/json_annotation.dart';

part 'article.g.dart';

@JsonSerializable()
class Article {
  int id = 0;
  String title = "";

  Article({this.id, this.title});

  factory Article.fromJson(Map<String, dynamic> json) =>
      _$ArticleFromJson(json);
  Map<String, dynamic> toJson() => _$ArticleToJson(this);
}

我有一个通用类,需要通过 fromJson -方法传递,请参见:

I have a generic class that needs to be passed the fromJson-method, see:

typedef CreateModelFromJson = dynamic Function(Map<String, dynamic> json);

class HttpGet<Model> {
  CreateModelFromJson createModelFromJson;

  HttpGet({
    this.createModelFromJson,
  });

  Future<Model> do() async {
    // [... make HTTP request and do stuff ...]
    return createModelFromJson(jsonData);
  }
}

最后,这是 ArticleService :

class ArticleService {
  Future<Model> read() => HttpGet<Article>({
    createModelFromJson: Article.fromJson,
  }).do();
}

这会在 createModelFromJson:Article.fromJson 中的红色 fromJson 中加下划线,错误是:

This underlines-in-red fromJson in createModelFromJson: Article.fromJson,, with the error being:

未为类"Article"定义吸气剂"fromJson".尝试导入定义"fromJson"的库,将名称更正为现有getter的名称,或者定义一个名为"fromJson"的getter或字段.dart(undefined_getter)

The getter 'fromJson' isn't defined for the class 'Article'. Try importing the library that defines 'fromJson', correcting the name to the name of an existing getter, or defining a getter or field named 'fromJson'.dart(undefined_getter)

很显然,编译器认为 .fromJson 是一个静态字段.但是,如上所述,它是一种静态工厂方法.

Obviously the compiler believes .fromJson to be a static field. However, it's, as can be seen above, a static factory method.

1.)您能帮忙如何将构造函数传递给泛型类吗?

1.) Can you help with how to pass the constructor to the generic class?

ALSO:
2.)我不确定是否真的会收到 Article ,还是必须先键入强制转换?我有点担心 typedef dynamic 返回类型.

ALSO:
2.) I'm not sure whether I'll actually get an Article back, or if I have to type cast it first? I'm kind of worried about the dynamic return type of the typedef.

3.)我也愿意为自己想做的事情提供更好的想法.

3.) I'm also open for better ideas for what I'm attempting to do.

推荐答案

Dart当前不支持允许使用构造函数作为替代品.我建议改为使用 static 方法.

Dart currently does not allow using constructors as tear-offs. I recommend using a static method instead.

或者,您可以只创建一个显式的闭包:

Alternatively you could just create an explicit closure:

class ArticleService {
  Future<Model> read() => HttpGet<Article>({
    createModelFromJson: (json) => Article.fromJson(json),
  }).do();
}

这篇关于在Dart中将类静态工厂作为方法参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆