0

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
manikanta
  • 8,100
  • 5
  • 59
  • 66

1 Answers1

1

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

class Foo {
  String key;

  Foo(this.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?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • Generic field do have benefit. With something like `Rx extends AppUser> currentUser` I can enforce the assignment to be of only sub types, like `currentUser = Rx()`, but not `currentUser = Rx()` – manikanta Sep 07 '21 at 17:15
  • Does Dart support `Rx extends AppUser> currentUser` or `Rx currentUser` or similar syntax for fields/properties? Thanks – manikanta Sep 07 '21 at 17:25
  • 1
    @manikanta Why wouldn't you just declare your field as `Rx currentUser` then? Or why not make the class generic? You also could make the member private and provide generic functions to get and set it (and cast to and from a base type). – jamesdlin Sep 07 '21 at 18:21
  • Ohhhh, Dart supports inheritance in generics too!!! `Rxn t = Rxn()` is valid in Dart. Just checked the syntax. I'm from Java background, and Java doesn't allow this. – manikanta Sep 07 '21 at 18:41
  • I could make class a generic one, but in this specific scenario, I will only have one `AuthService` for all types of user. So having user type as generic in `AuthService` doesn't make sense here. Thanks – manikanta Sep 07 '21 at 18:43