从 dart 中的静态函数访问 class 中的类型参数的解决方法

Workaround for accessing type parameters in class from a static function in dart

我正在尝试创建一个包装器 class 其中的哪些方法需要是静态的并且 class 应该是通用的 所以,我写:

class Resource<T> {
     Resource({@required this.status, this.data, this.message});

     String message;
     Status status;
     T data;

     static Resource<T> success(T data) =>
        Resource(status: Status.SUCCESS, data: data);

     static Resource<T> error(String msg, T data) =>
        Resource(status: Status.ERROR, data: data, message: msg);

     static Resource<T> loading(T data) =>
        Resource(status: Status.LOADING, data: data)
}

所以,我可以这样使用它:

Resource<T> handleSuccess(data: T) {
    return Resource.success(data)
}

但是,我得到一个错误 static members can't reference type parameters of the class

是否有解决此行为的方法?

两种选择。使静态方法通用:

     static Resource<T> success<T>(T data) =>
        Resource(status: Status.SUCCESS, data: data);

     static Resource<T> error<T>(String msg, T data) =>
        Resource(status: Status.ERROR, data: data, message: msg);

     static Resource<T> loading<T>(T data) =>
        Resource(status: Status.LOADING, data: data);

或将它们引入工厂构造函数:

     factory Resource.success(T data) =>
        Resource(status: Status.SUCCESS, data: data);

     factory Resource.error(String msg, T data) =>
        Resource(status: Status.ERROR, data: data, message: msg);

     factory Resource.loading(T data) =>
        Resource(status: Status.LOADING, data: data)

两者都应该有效。主要区别在于如果要显式提供类型参数,则将其放置在何处。或者:

  Resource.data<int>(42)  // Static method

  Resource<int>.data(42);  // factory.