Firebase Authentication in Flutter
Firebase is a tool created by Google that can support user authentication, cloud database storage, and much more. Today we’ll talk about how to use Firebase’s authentication service to sign up and log in users in a flutter application.
First off, make a new firebase project at https://console.firebase.google.com/u/0/ and follow the instructions for linking it with an android and iOS app.
Once the setup is completed, you must add the appropriate dependency to your pubspec.yaml file. The dependency you need is:
and at the top of your dart file add the line:
Add the line:
final FirebaseAuth _auth = FirebaseAuth.instance;
as an instance variable to the top of your dart code as well.
To initiate the sign up process, and to create a new user, we use the .createUserWithEmailAndPassword() method.
In this example, I used TextEditingControllers for both the email and password fields, and gave their respective contents to the .createUserWithEmailAndPassword() method. This method is called when the “sign up” button is pressed, and uses a Form widget with validation parameters to ensure that the two textfields have usable information.
Log In Existing Users
To log in an existing user, we use the .signInWithEmailAndPassword() method.
The text controllers are used in the same fashion as the sign up method.
Auto Log in
If at any time, especially when the app first loads, you wish to get the current user, you can use the currentUser() method.
This is especially useful for auto-login for existing users. For example, in my app, I call this method in the initState() function to auto-login my users if a current user is found. Once a user opens the app, it will auto sign them in if they have signed in once before.
Full example code (with no UI features):