1

How to access a class "fromMap" factory constructor from a Generic class.

For example, Here is a very simplified class and method:

    abstract class DBbase<T> {
      dynamic convert(dynamic input) {
        T u = T.fromMap(input.toMap());
        return u;
      }
    }
    class DB<UserModel> extends DBbase {}

The **"T.fromMap" ** doesn't work a although the "UserModel" does have the method within.

If I change that line to:

    UserModel u2 = UserModel.fromMap(input.toMap());

then it works, but this defeats the purpose of defining the type as a generic.

  • You cannot. Instead consider having the caller pass a callback to your function to construct an object of the desired type. – jamesdlin Dec 07 '21 at 22:44
  • Thank you for your comment. I have done that in the past but with all the generic programming under-the-hood, I'd hope there was a way to do it generically based on the Model passed in as T – Rudy Folden Dec 07 '21 at 23:11
  • I think you can read this one https://stackoverflow.com/questions/42004475/how-to-create-a-generic-method-in-dart – CrimsonFoot Dec 08 '21 at 06:24

0 Answers0