Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: generics abstract static methods

Tags:

oop

dart

Dears

I want to have abstract generic class with the following pattern My phone model is as follows:

  class Phone extends ModelInterface {
  ...

  @override
  static dynamic getErrorInstance(Map<String, dynamic> map) {
    return Phone.fromErrors(map);
  }

  @override
  static dynamic getResponseInstance(Map<String, dynamic> map) {
    return Phone.fromMap(map);
  }
}

As you can see the Phone model extends ModelInterface and there are two overriden methods getErrorInstance and getResponseInstance

These two methods are defined as static in the ModelInterface abstract class

abstract class ModelInterface {
  static dynamic getErrorInstance(Map<String, dynamic> map) {}
  static dynamic getResponseInstance(Map<String, dynamic> map) {}
}

What I wanted to do is to create a generic method that builds the object based on response type shown below

abstract class Base {
  ...

  T getModel<T extends ModelInterface>(Map<String, dynamic> map) {
    if (hasErrors(map)) {
      return T.getErrorInstance(map);
    }

    return T.getResponseInstance(map);
  }
}

And the client for this method getModel shown below

class UserAuth extends Base {
  Future<Phone> registerPhone(Phone phone) async {
    String url = Routes.phoneUrl;
    String body = json.encode(phone.toMap());
    final response = await http.post(url, body: body, headers: Routes.headers);
    final responseBody = json.decode(response.body);
    // here I want the generic type to be phone
    return getModel<Phone>(responseBody);
  }
}

However I am getting this error

enter image description here

Thanks

like image 230
xiarnousx Avatar asked Oct 25 '25 00:10

xiarnousx


1 Answers

Actually I fixed it by passing in another generic Parameter such as below

  T getModel<T extends ModelInterface>(Map<String, dynamic> map, T) {
    if (hasErrors(map)) {
      return T.getErrorInstance(map);
    }

    return T.getResponseInstance(map);
  }

And for the client code I added the below

class UserAuth extends Base {
  Future<Phone> registerPhone(Phone phone) async {
    String url = Routes.phoneUrl;
    String body = json.encode(phone.toMap());
    final response = await http.post(url, body: body, headers: Routes.headers);
    final responseBody = json.decode(response.body);

    return getModel<Phone>(responseBody, Phone.empty());
  }
}
like image 76
xiarnousx Avatar answered Oct 28 '25 03:10

xiarnousx