Generic field/method in non-generic class in Dart


Is it possible, in Dart, to have generic methods in non-generic class, like in Java?

I use Getx for state management, DI & routing, but this question is not specific to Getx or Flutter.

I’ve AuthService which deals with authentication and sets logged in user, like Rxn<AppUser>. I’ve 3 types users: Customer extends AppUser, Seller extends AppUser & Admin extends AppUser.

I want to change the user observable to something like this: Rxn<? extends AppUser> currentUser = Rxn().

I tried below syntax, but doesn’t work.

class AuthService extends GetxService {
  T Rxn<T extends AppUser> currentUser = Rxn();

Direct answer to my question:
Dart supports inheritance in generic types too (unlike in Java). So, Rxn<AppUser> currentUser = Rxn<Patient>() is possible in Dart. I don’t need wildcard or any. Thanks to @jamesdlin for his answer/comments.


You can have generic methods. You’d declare them the same way as you’d declare generic functions:

class Foo {
  String key;


  Map<String, T> f<T>(T value) => <String, T>{key: value};

However, it doesn’t make sense to have generic fields. A field represents a data member; what data would be stored and where when the type isn’t known yet? Would you store a potentially infinite number of data members for every possible value of T?

Answered By – jamesdlin

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *