Search code examples
flutterdartfirebase-authentication

How to Subclass FirebaseAuth User Class in Flutter


I'm new to Flutter/Dart and cannot figure out how to subclass the FirebaseAuth User class. I have been watching a rather old Firebase tutorial so I have had to change things a bit as the API has changed over the years.

The tutorial simply wanted me to do this:

class User {

  final String uid;
  
  User({ this.uid });

}

But since the new FirebaseAuth API has a class named User I figured I would simply subclass it as such:

import 'package:firebase_auth/firebase_auth.dart';

class BrewUser extends User {
  final String uid;

  BrewUser({required this.uid});
}

The error on the constructor of BrewUser is:

The class 'User' doesn't have an unnamed constructor. Try defining an unnamed constructor in 'User', or invoking a different constructor.dartundefined_constructor_in_initializer

The only constructor I see in the User class is private and looks like this:

  User._(this._auth, this._delegate) {
    UserPlatform.verify(_delegate);
  }

Solution

  • I recommend against subclassing here. Instead have your own BrewUser class wrap the User from Firebase Authentication:

    class BrewUser {
      final User user; // https://pub.dev/documentation/firebase_auth/latest/firebase_auth/User-class.html
    
      BrewUser({required this.user});
    }
    

    That way you can expose and access whatever you need from the Firebase user, but you're not bound/limited by its implementation.

    This might be an interesting read on this topic too: Composition over inheritance but