logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Handling User Authentication in Flutter

author
Generated by
Nitish Kumar Singh

21/09/2024

Flutter

Sign in to read full article

User authentication is a crucial component of most applications. It ensures that only authorized users can access certain functionalities within your app. In Flutter, there are numerous ways to handle user authentication, but Firebase Authentication has emerged as a popular solution due to its ease of integration and robustness. In this post, we’ll delve into setting up Firebase Authentication in a Flutter app.

Step 1: Setting Up Firebase

Before implementing authentication, you need to create a Firebase project. Here’s how you can do that:

  1. Create a Firebase Project: Go to the Firebase Console and click on "Add project". Follow the instructions to set up a new project.

  2. Register Your App: Once the project is created, click on "Add app", select the platform (Android/iOS) and follow the steps to register your app.

  3. Enable Authentication: In the Firebase console, navigate to the "Authentication" section. Enable the sign-in methods you want (Email/Password, Google Sign-In, etc.).

Step 2: Adding Firebase Dependencies to Your Flutter Project

Open your pubspec.yaml file and include the necessary dependencies for Firebase:

dependencies: flutter: sdk: flutter firebase_core: ^x.x.x firebase_auth: ^x.x.x

Make sure to replace ^x.x.x with the latest version numbers found on pub.dev.

Now, run flutter pub get in your terminal to install these packages.

Step 3: Initializing Firebase in Your Flutter App

Before using Firebase services, you need to initialize Firebase in your app. Modify your main.dart file as shown below:

import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'home_page.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Authentication', theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePage(), ); } }

Step 4: Implementing User Authentication

Let's create a simple user interface for login and registration.

Create a new file named auth_service.dart for authentication logic:

import 'package:firebase_auth/firebase_auth.dart'; class AuthService { final FirebaseAuth _auth = FirebaseAuth.instance; // Register user Future<User?> registerWithEmailAndPassword(String email, String password) async { UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password); return result.user; } // Sign in user Future<User?> signInWithEmailAndPassword(String email, String password) async { UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password); return result.user; } // Sign out Future<void> signOut() async { await _auth.signOut(); } }

Now, create a simple login form in your home_page.dart:

import 'package:flutter/material.dart'; import 'auth_service.dart'; class HomePage extends StatelessWidget { final AuthService _auth = AuthService(); final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("User Authentication"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( controller: _emailController, decoration: InputDecoration(labelText: 'Email'), ), TextField( controller: _passwordController, decoration: InputDecoration(labelText: 'Password'), obscureText: true, ), SizedBox(height: 20), ElevatedButton( onPressed: () async { User? user = await _auth.signInWithEmailAndPassword( _emailController.text, _passwordController.text ); if (user != null) { print('Successfully logged in: ${user.email}'); } else { print('Failed to log in'); } }, child: Text('Login'), ), ElevatedButton( onPressed: () async { User? user = await _auth.registerWithEmailAndPassword( _emailController.text, _passwordController.text ); if (user != null) { print('Successfully registered: ${user.email}'); } else { print('Failed to register'); } }, child: Text('Register'), ), ], ), ), ); } }

Step 5: Handling Authentication State

To manage authentication state throughout your application, you can use the StreamBuilder widget to listen to changes in user sign-in state.

Modify the HomePage widget to handle user state:

class HomePage extends StatelessWidget { final AuthService _auth = AuthService(); @override Widget build(BuildContext context) { return StreamBuilder<User?>( stream: _auth.authStateChanges(), // Add this line for the stream builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.active) { User? user = snapshot.data; if (user == null) { return LoginScreen(); // Redirect to login screen } else { return LoggedInScreen(user: user); // Redirect to the logged-in screen } } else { return Center(child: CircularProgressIndicator()); } }, ); } }

In this example, upon creating your application, users will be directed to login or register based on whether they are currently logged in.

Implementing user authentication in a Flutter application may seem daunting at first, but by following these guidelines and utilizing Firebase properly, it can become a smooth and straightforward process. Now you can build more secure applications and ensure that your users' data remains protected!

Popular Tags

FlutterUser AuthenticationFirebase

Share now!

Like & Bookmark!

Related Collections

  • Flutter Development: Build Beautiful Apps

    21/09/2024 | Flutter

Related Articles

  • Local Storage in Flutter

    21/09/2024 | Flutter

  • Building Layouts with Flutter

    21/09/2024 | Flutter

  • Deploying Flutter Apps to App Stores

    21/09/2024 | Flutter

  • Navigating Between Screens in Flutter

    21/09/2024 | Flutter

  • Performance Optimization in Flutter Apps

    21/09/2024 | Flutter

  • Introduction to Flutter and Dart

    21/09/2024 | Flutter

  • Testing Flutter Applications

    21/09/2024 | Flutter

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design