最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flutter - How to instantiate T with parameters from within a generic in dart - Stack Overflow

programmeradmin1浏览0评论

I have a Flutter application (using Dart) where I retrieve data from my Firestore in the form of json.

I have several model classes that I want to convert to and from JSON. Let's say I have the class A. Serializing is easy because it can be an instance method. However, for deserializing (instantiating A), there are several ways:

class A {
  late String name;
  late String email;

  A({required this.name, required this.email});

  Map<String, dynamic> toJson() {
    return {'name': name, 'email': email};
  }

  // Option 1: Constructor
  A.fromJson(Map<String, dynamic> jsonData) {
    name = jsonData['name'];
    email = jsonData['email'];
  }

  // Option 2: Factory constructor
  factory A.fromJsonFactory(Map<String, dynamic> jsonData) {
    return A(name: jsonData['name'], email: jsonData['email']);
  }

  // Option 3: Static method
  static A fromJsonStatic(Map<String, dynamic> jsonData) {
    return A(name: jsonData['name'], email: jsonData['email']);
  }
}

However, I want to instantiate it from within a generic using the jsonData:

class Repository<T extends ModelBase> {
  void onData(Map<String, dynamic> jsonData) {
    // This is just an example
    print(T.fromJson(jsonData));
  }
}

To that effect, I have attempted the toJson behavior to be inheritable and declared in a superclass (ModelBase). I have attempted A to extend or implement ModelBase, but seems like I can't get to force the inheritors to implement it, nor can I call it from the generic.

I guess, generalizing, my question is:

  • How do I need to define ModelBase (which will be T) ?
  • What do I need to tell the the generic about T ?

So that I can instantiate T (with parameters, not a parameterless constructor) inside the generic of T in Dart?

发布评论

评论列表(0)

  1. 暂无评论