Skip to content
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
flutter app development

Let Me Flutter

Flutter apps development site

  • Home
  • Flutter App Development
    • Flutter Solutions
      • Tech
      • Setup
        • How To Make Your First App With Flutter?
      • How To Get Flutter Android App Using Flutter Build Apk
    • Dart Fundamentals
      • Flutter Loops
        • How To Easily Use For Loop In Flutter Widgets
        • How To Easily Use ForEach Loop In Flutter
        • How To Easily Use While Loop In Flutter
        • How To Easily Use Flutter For In Loop
        • How To Easily Use Flutter For Loop Index
      • Flutter Lists
        • How To Easily Use List In Flutter Dart
        • [Top 4 Ways] How To Properly Combine Lists In Dart
        • How To Reverse List In Flutter – Easy Flutter Code Example
        • How To Convert List To Set In Flutter – Easy Flutter Code Examples
        • How To Shuffle List In Flutter – Easy Flutter Code Examples
      • Flutter If Else Condition
        • How To Use If Else In Flutter – Easy Flutter Guide
      • Flutter Switch Case
        • How To Easily Use Flutter Switch Statement
      • Flutter Functions
        • How To Easily Use Flutter Function
      • Flutter Maps
        • How To Easily Create And Use Flutter Map List
        • How To Easily Create And Use Flutter Map – Easy Flutter Guide
      • Flutter Variables
        • How To Easily Convert Dart Double to Int (4 Easy Ways)
        • How To Easily Convert Dart Int To String
        • How To Easily Convert Double To String Flutter
        • How To Easily Convert Flutter String To Double
        • How To Easily Convert Flutter String To Int – Easy Flutter Guide
        • How To Perform Flutter String Concatenation [Top 4 Ways]
    • Flutter Web Templates
      • Flutter Web Template – Flutter Web Drawer Widget Example
    • Mobile Templates
      • Instagram UI Template
        • Instagram News Feed UI In Flutter-Beautiful Flutter Design-Flutter Instagram Template Part 1
      • Flutter Forms
        • Signup Flutter Form UI Design-Beautiful Flutter UI Template
        • Flutter Glassmorphism Login UI Template With Source Code
        • Signup Flutter Form UI Design 2022-Beautiful Flutter UI Template
        • Beautiful Flutter Login Template – Flutter templates 2022
        • Gradient Flutter Login UI Form Template With Source Code – Flutter Templates 2022
        • Beautiful Flutter Login UI Form Template
        • Beautiful Flutter Login Page UI Design – Example Code
        • How To Design Beautiful Flutter Login Screen UI
        • How To Design Beautiful Flutter Login Form Template – Easy Flutter Code
        • How To Create Beautiful Flutter Login Form Design UI Template
    • Widgets
      • Menus
        • Flutter Popup Menu Button Detailed Customization With Example-2022 Flutter Guide
      • Sliders
        • Flutter Carousel Slider
          • How To Easily Set Flutter Carousel Slider Full Width
          • How To Easily Use Flutter Carousel Slider OnPageChanged
          • How To Easily Customize Flutter Carousel Slider AutoPlay
        • Flutter Carousel Slider Beautiful Customization With Example
        • Flutter Range Slider Beautiful Customization With Example | Syncfusion
      • Stack
        • Flutter App Stack Widget Detailed Explanation With Example
      • Buttons
        • Flutter Icon Button Example – Detailed Customization – Step By Step
        • Flutter Raised Button Example – Detailed Raised Button Decoration
        • Flutter Elevated Button
          • How To Easily Change Flutter Elevated Button Color
          • How To Change Flutter Elevated Button Border Radius
          • How To Easily Customize Flutter Elevated Button Width
          • How To Easily Customize Flutter Elevated Button Height – Top 2 Methods
          • How To Easily Use Flutter Elevated Button OnPressed
        • Flutter Floating Action Button
          • How To Easily Customize Flutter FloatingActionButton Widget
      • Icons
        • How To Use Icons In Flutter? Font Awesome Icons In Flutter
        • How To Easily Change Flutter Icon Size – Flutter Example Code
      • Flutter Card Widget
        • All You Need To Know About Flutter Card Widget – Explained With Example
        • How To Easily Customize Flutter Card Border Radius
        • How To Easily Customize Flutter Card Border Radius
        • How To Change Flutter Card Color – Easy Flutter Guide
        • How To Change Flutter Card Elevation – Easy Flutter Guide
        • How To Change Flutter Card Shadow Color – Easy Flutter Guide
        • How To Easily Customize Flutter Card Height – Top 2 Methods
      • Flutter Drawer Widget
        • Beautiful Flutter Drawer Widget Customization-Explained With Example
        • How To Change Flutter Drawer Icon Color – Easy Flutter Guide
        • How To Change Flutter Drawer Width – Easy Flutter Code Example
        • How To Easily Change Flutter Drawer Background Color
        • How To Change Flutter Drawer Header Height – Easy Flutter Code Example
      • Appbars
        • How To Design Beautiful AppBar in Flutter
        • Let’s Customize AppBar In Flutter
        • Flutter SliverAppBar Customization [Easy Guide]
        • Flutter Appbar Actions Customization [Detailed Guide]
        • How To Change Flutter Appbar Color In Flutter App-2022 Guide
        • How To Customize Flutter Appbar Leading- 2022 Guide
        • How To Make Flutter Appbar Title Center-2022 Guide
        • How To Implement Flutter Appbar Transparent
        • How To Change Flutter Appbar Height
        • How To Remove Flutter Appbar Elevation
        • How To Change Flutter Appbar Shadow Color
        • How To Easily Change Flutter Appbar Background Color
        • How To Easily Customize Flutter Appbar Back Button
        • How To Easily Set Flutter Appbar Center Text
        • How to Easily Change Flutter Appbar Default Height
        • How To Easily Change Flutter Appbar Icon Color Theme
      • Flutter Textfield
        • Change Flutter Textfield Cursor Color Explained With Example-Best Flutter Guide
        • Flutter Textformfield Default Value Explained With Example
        • Flutter Textfield Onchanged Explained With Example-Best Flutter Guide
        • Flutter Textfield Remove Underline Explained With Example
        • How To Change Flutter Textfield Underline Color
        • How To Implement Flutter Textfield Disable?
        • How To Change Flutter Textfield Height?
        • How To Customize Flutter Textfield Label?
        • How To Customize Flutter Textfield Hint Text?
        • How To Change Flutter Textfield Hint Text Color?
        • How To Customize Flutter Textfield Initial Value?
      • Flutter Textformfield
        • How To Change Flutter Textformfield Background Color
        • How To Set Flutter Textformfield Default Value?
        • How To Change Flutter Textformfield Color?
        • How To Customize Flutter Textformfield KeyboardType?
        • How To Change Flutter Textformfield Border Color?
        • How To Implement Flutter Textformfield Remove Underline?
        • How To Change Flutter Textformfield Underline Color?
        • How To Change Flutter Textformfield Hint Text Size?
        • How To Change Flutter Textformfield Font Size?
        • How To Change Flutter Textformfield Hint Text Color?
        • How To Implement Flutter Textformfield Hint Text Center?
        • How To Change Flutter Textformfield Error Text
        • How To Change Flutter Textformfield Error Style
        • How To Change Flutter Textformfield Text Color
        • How To Change Flutter Textformfield Outline Border Color
        • How To Change Flutter Textformfield Outline Border Width
        • How To Change Flutter Textformfield Label Text
      • Flutter Dropdown
        • How To Change Flutter Dropdown Icon
        • How To Implement Flutter Dropdown Remove Underline
        • How To Change Flutter Dropdown Icon Color
        • How To Change Flutter Dropdown Background Color
        • How To Change Flutter Dropdown Border Radius
        • How To Change Flutter Dropdown Icon Size
        • How To Implement Flutter Dropdown OnChange
      • Flutter ListViews
        • How To Implement Flutter ListView Horizontal
        • How To Implement Flutter ListView Builder Horizontal
      • Flutter Popup Menu
        • How To Use Flutter Popup Menu Item Ontap
        • How To Change Flutter Popup Menu Shape
        • How To Change Flutter Popup Menu Width
        • How To Change Popup Menu Icon Flutter
        • How To Change Flutter Popup Menu Item Height
        • How To Change Flutter Popup Menu Icon Size
      • Flutter SingleChildScrollView
        • How To Use Flutter SingleChildScrollView
      • Flutter Raised Button
        • How To Change Flutter RaisedButton Width
        • How To Change Flutter RaisedButton Color
        • How To Change Flutter RaisedButton Shape
        • How To Use Flutter RaisedButton OnPressed
        • How To Implement Flutter RaisedButton Disable
        • How To Change Flutter RaisedButton Disabled Color
        • How To Change Flutter RaisedButton Size
        • How To Easily Use Flutter RaisedButton Icon
        • How To Use Flutter Raisedbutton Icon OnPressed
        • How To Change Flutter Raised Button Elevation
      • Flutter Icon Button
        • How To Change Flutter Icon Button Background Color
        • How To Change Flutter Icon Button Size
        • How To Use Flutter Icon Button OnPressed
      • Flutter Flat Button
        • How To Easily Change Flutter FlatButton Color
      • Flutter Text Widget
        • How To Easily Set Flutter Text Align Center
        • How To Easily Change Flutter Text Font Size
        • How To Easily Change Flutter Text Size
        • How To Make Flutter Text Bold-Example Code
        • How To Change Flutter Text Color-Example Code
        • How To Set Flutter Text Italic-Easy Flutter Code Example
        • How To Change Flutter Text Line Height-Easy Flutter Code Example
        • How To Easily Set Flutter Text Underline
        • How To Easily Add Flutter Text Shadow
        • How To Easily Set Flutter Text Word Spacing
        • How To Easily Set Flutter Text Letter Spacing
        • How To Easily Set Space Between Flutter Text And Underline
        • How To Easily Align Flutter Text Justify
        • How To Easily Change Flutter Text Underline Color
      • Flutter Images
        • Learn How To Use Flutter Image Asset-Easy Flutter Guide
      • Flutter Column Widget
        • How To Easily Set Flutter Column Align Left
        • How To Easily Implement Flutter Column Scrollable
        • How To Easily Customize Flutter Column Spacing
      • Flutter Snackbar
        • How To Easily Use Flutter Snackbar Widget
      • Flutter Wrap Widget
        • How To Easily Use Flutter Wrap Widget – Flutter Example Code
      • Flutter Container Border Customization[Detailed Guide]
      • Flutter SizedBox Widget
        • How To Easily Customize Flutter SizedBox Widget
      • Flutter InkWell Widget
        • How To Easily Use Flutter InkWell OnTap
      • Textfield In Flutter App Detailed Explanation With Example
      • Flutter Textfield Align Center With Example
      • Flutter Image Picker
        • How To Properly Use Flutter Image Picker – Easy Flutter Example
      • Flutter Container Widget
        • How To Easily Change Flutter Container Size
        • How To Easily Set Flutter Container Full Width
        • How To Easily Customize Flutter Box Shadow Offset
        • How To Easily Customize Flutter Container Shadow
        • How To Easily Change Flutter Container Border Radius
        • How To Easily Change Flutter Container Padding
        • How To Easily Change Flutter Container Color
        • How To Easily Add Flutter Container Background Image
        • How To Easily Change Flutter Container Shadow Color
        • How To Easily Change Flutter Container Height
        • How To Easily Customize Flutter Container Margin
        • How To Easily Implement Flutter Container Gradient
        • How To Easily Set Flutter Box Shadow Only Top
        • How To Easily Implement Flutter Container Shape Circle
        • How To Easily Change Flutter Container Alignment
      • Beautiful Bottom Navigation Bar In Flutter App-Android And Flutter IOS-Dart Flutter
      • Let’s Customize Texts In Flutter
      • How To Change Flutter Textfield Color [Easy Examples]
      • Flutter Textfield Border Radius Explained With Example-Best Flutter Guide
      • Flutter Glassmorphism
        • How To Easily Customize Flutter Glassmorphism Container
        • How To Easily Change Flutter Glassmorphism Container Size
      • Flutter Icon Button Example – Detailed Customization – Step By Step
      • Flutter SetState
        • How To Easily Use Flutter SetState
      • Flutter Positioned Widget
        • How To Easily Use Flutter Positioned Widget – Example Code
      • Flutter Padding
        • How To Use Flutter Padding – Easy Flutter Guide
      • Flutter Bottom Navigation Bar Customization
      • Neumorphic Effect In Flutter App Container Widget
      • How To Change Flutter Textfield Border Color
      • Container Customization In Flutter App
      • Flutter Textfield Only Numbers Explained With Example-Best Flutter Guide
      • Flutter Gesture Detector Widget
        • How To Easily Use Flutter GestureDetector OnTap
      • Flutter Textfield Maxlength Detailed Explanation With Example-Best Flutter Guide
      • How To Use Flutter Column Widget – Detailed Examples
      • Flutter Textfield Decoration Detailed Explanation With Example-Flutter Guide 2022
      • Beautiful Grid View Builder In Flutter App-Detailed Customization
      • ListView Builder In Flutter Apps
      • Flutter Table Widget
        • How To Easily Customize Flutter Table Widget
      • How To Use Rows In Flutter Apps
      • How To Change Flutter Textfield Font Size
    • React Native
      • React Native Jobs In 2023: All You Need To Know
      • Why Should I Learn React Native Framework In 2023
      • Right React Native Elements for Your Next App [Detailed Guide]
      • Benefits Of Creating A React Native App [Easy Guide]
    • Updates
      • What’s New in Flutter 2.10 release?
    • Animations
      • Animated Container
        • How To Use Animated Container In Flutter? Explained With Example
      • Animated Texts
        • Animated Text Kit In Flutter App-Dart Flutter Makes Animation Easy
      • Lottie Animations
        • How To Use Beautiful Lottie Animations In Flutter App
      • Hero Animations
        • Hero Animations In Flutter App With Example-Beautiful Flutter Animations In Dart Language
  • Python Programming
    • Python Tuples
      • How To Easily Create Python Tuple – Easy Python Guide
    • Python Dictionaries
      • How To Properly Define And Use Python Dictionary – Easy Python Code Example
      • How To Properly Use Python Dict To Create Dictionary – Easy Python Guide
      • How To Use Python Dictionary Get Method – Easy Python Code Example
      • How To Use Python Dictionary Pop Method – Easy Python Guide
      • How To Use Python Dictionary SetDefault Method – Easy Python Guide
      • How To Use Python Dictionary Clear Method – Easy Python Code Example
    • Python Del Keyword
      • How To Properly Use Python Del Keyword – Easy Python Code
    • Python If Else Statement
      • How To Easily Use Python If Else Statement
      • How To Use Python Elif Statement – Easy Python Guide
      • How To Easily Use Nested If In Python
    • Python Loops
      • Python For Loop
        • How To Easily Use Python For Loop – Python Code Examples
      • Python While Loop
        • How To Use Python While Loop – Easy Code Examples
    • Python Break and Continue
      • Python Break Statement
        • How To Easily Use Python Break Statement – Python Code Examples
      • Python Continue Statement
        • How To Easily Use Python Continue Statement
    • Python Pass Statement
      • How To Easily Use Python Pass Statement
    • Python Functions
      • How To Properly Use Python Function – Super Easy Python Guide
      • How To Properly Use Python Function Arguments – Easy Python Guide
      • How To Properly Use Python Lambda Function – Easy Python Guide
    • Python Variables
      • How To Define And Use Python Global Variable – Easy Python Guide
      • How To Properly Use Python Local Variable – Easy Python Guide
      • How To Properly Use Python NonLocal Variables – Easy Python Guide
    • Python Classes and Objects
      • How To Properly Define And Use Python Class – Easy Example Code
    • Python Lists
      • How To Easily Use Python List Pop Method
      • How To Properly Use Python List Remove Method – Easy Python Guide
      • How To Properly Use Python List Extend – Easy Python Guide
      • How To Properly Use Python List Insert – Easy Python Guide
      • How To Easily Use Python List Index Method – Python Example Code
      • How To Easily Use Python List Count Method – Python Example Code
      • How To Easily Use Python List Reverse Method
      • How To Easily Use Python List Sort Method
      • How To Properly Use Python List Copy Method – Easy Python Guide
      • How To Easily Use Python List Clear Method
      • How To Easily Create Python List – Easy Python Example Code
      • How To Properly Use Python List Append – Easy Python Code
      • How To Easily Convert Python List To String
      • How To Easily Get Python List Size – Top 2 Methods
  • Code Compiler
  • Free SEO Tools
  • More
    • About Us
    • Disclaimer
    • Contact Us
    • Privacy Policy
  • Toggle search form
flutter firebase email authentication

Flutter Firebase Email Authentication [Login, Signup, Logout]

Posted on January 29, 2023 By ZeeshanAli No Comments on Flutter Firebase Email Authentication [Login, Signup, Logout]

In this tutorial, we’ll learn how to properly implement Flutter Firebase email authentication which includes login, signup, and logout.

Everything from building user interfaces to functions used to send and receive data from Firebase will be practically covered in this tutorial.

Outline

  1. Introduction: Flutter Firebase Email Authentication
  2. Implementing Firebase Email and Password Authentication in Flutter App (Step By Step)
  3. Source Code of Flutter Firebase Email Authentication Program
  4. Conclusion

Introduction: Flutter Firebase Email Authentication

We’ll be implementing email and password authentication in our Flutter app using Firebase. The concepts we will cover in this tutorial are listed below:

Register – Register a new user in Firebase.

Login – Login/authenticate a user using email and password and navigate him/her to the home screen.

Signout – Logout the user from the home screen and navigate him/her to the login screen.

So let’s start creating it without any more delay.

Implementing Firebase Email and Password Authentication in Flutter App (Step By Step)

Follow the below steps in order to properly understand the implementation of Flutter Firebase email authentication.

Step 1: Setup Firebase

We’ve written a detailed article on how to properly set up Firebase and connect it to your Flutter project.

Click here to perform the Firebase setup process.

Only follow the first step which is titled ‘Step 1: Setup Firebase’. Then come here again to complete the setup process for authentication using Firebase.

Import Firebase Auth Package

firebase_auth: ^4.2.5

Import this package in the dependencies section of your Flutter project’s pubspec.yaml file shown in the below image. Click here to get the latest version of Firebase auth.

flutter pubspec yaml dependencies firebase auth package

import 'package:firebase_auth/firebase_auth.dart';

Use this line in the file where you want to specify the firebase operations. In our case, we’ve specified everything in the main.dart file so we’ve used this import statement inside it.

Step 2: Initialize Firebase

import 'package:firebase_core/firebase_core.dart';
Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}
Replace your app main() method with this one. It’s important to initialize the Firebase so it can work properly.

Step 3: Activate Email Sign In Authentication

For that, open your Firebase project and click on authentication. Then click on get started and choose email/password. Enable it and click on save as shown in the below image.

firebase email password authentication allow

Step 4: Creating UI (Login, Register, Home)

The source code will be provided at the end of this article. In the meantime, let’s look at the screens.

Screen 1: Login

flutter login screen ui template having flutter textfields and flutter material button

flutter login screen ui template having flutter textfields and flutter material button

flutter snackbar widget

This UI has an email and password Flutter textfield and is used to fetch and store data from users. Also, it has a Flutter material button which is used to validate data entered by the user.

If the user enters an email that is not registered, then a Flutter snack bar widget will appear which will show a custom text. Else, the user will be navigated to the home screen.

Also, a Flutter circular progress indicator widget will be shown during the validation process. See the above images for visualization.

We’ve created a custom toggle that is used to show the login or registration screen. Click on it and it’ll show the registration screen if the current one is login and vice versa.

Screen 2: Register

flutter signup screen ui template having flutter textfields and flutter material button, flutter text widgets and flutter container widgets

flutter snackbar widget

It’s used to register a new user in Firebase using email and password. It’ll check if the current email entered by the user is already present then it’ll display a snack bar. If not, then it’ll navigate the user to the home screen.

Screen 3: Home with Logout Button

flutter home screen UI with flutter appbar, appbar actions, flutter text widget, flutter container widget

This screen will show the email address of the logged-in user. We’ve displayed the email address using the Flutter text widget. Also, we’ve decorated it using a Flutter container widget to make it look less boring.

The sign-out button in the actions section of the Flutter app bar widget is used to log out the user. We’ve used stream which will continuously check the state of the user. If it’s logged out then it’ll show the login screen. If not, then it’ll display on the home screen.

If we close the app and reopen it, then if the user was logged in then it’ll show the home screen. If logged out, then it’ll show the login screen.

Step 5: Firebase Operations

We’ve created a simple class and inside it, we’ve specified the Firebase operations. First, we’ve created an instance of the Firebase auth class. See below:

final FirebaseAuth auth = FirebaseAuth.instance;

1. Login User

 Future<void> signIn(email, password) async {
    await auth.signInWithEmailAndPassword(email: email, password: password);
  }
This method is used to log in a user with a valid email and password.

2. Register User

 Future<void> register(email, password) async {
    await auth.createUserWithEmailAndPassword(email: email, password: password);
  }

This method is used to register a new user using email and password if the same email is not registered yet.

3. Sign out User

  Future<void> signOut() async {
    await auth.signOut();
  }

It’s used to log out the current(logged-in) user.

Step 6: Auth Status and Stream

Stream<User?> get authStateChanges => auth.authStateChanges();

It’s used to check the status of whether the user is logged in or logged out.

StreamBuilder(
      stream: AuthClass().authStateChanges,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return HomeScreen();
        } 
       else {
          return LoginAndRegisterScreen();
        }
      },
    )
This will check if the user is logged in, then show the home screen. If logged out, then show the login screen.

Step 7: Current User Data

User? get currentUser => auth.currentUser;  // inside Auth class

final User? user = AuthClass().currentUser;   // inside home screen widget
Text(
       //display logged in user email address
     user!.email!.isEmpty ? 'No data' : user!.email.toString()
       )

So this is how we can easily create Flutter Firebase email authentication. Hope you’ve learned a lot from this tutorial. Do feel free to share it with our Flutter programmers.

Click here to learn how to create a Flutter CRUD app using Firestore.

The complete source code of this whole program of email authentication using Flutter firebase is provided in the below section.

Source Code of Flutter Firebase Email Authentication Program

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Firebase Email Authentication App',
        home: ChooseScreen());
  }
}

class ChooseScreen extends StatelessWidget {
  const ChooseScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: AuthClass().authStateChanges,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return HomeScreen();
        } else {
          return LoginAndRegisterScreen();
        }
      },
    );
  }
}

class LoginAndRegisterScreen extends StatefulWidget {
  const LoginAndRegisterScreen({super.key});
  @override
  State<LoginAndRegisterScreen> createState() => _LoginAndRegisterScreenState();
}
class _LoginAndRegisterScreenState extends State<LoginAndRegisterScreen> {

  bool loginScreenVisible = true;
  bool showLoading = false;
  String email = '';
  String password = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(loginScreenVisible ? 'Login' : 'Signup'),
        backgroundColor: Colors.purple,
      ),

      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(horizontal: 50, vertical: 200),
        child: Column(
          children: [

            inputField('email'),
            inputField('password'),
            !loginScreenVisible ? SizedBox() : forgotPassword(),
            loginRegisterButton(),
            toggleIconButton()

          ],
        ),
      ),
    );
  }

  /// Flutter textfield ///
  Widget inputField(fieldType) {
    return Padding(
      padding: EdgeInsets.only(bottom: 10),
      child: TextField(
        onChanged: (value) {
          setState(() {
            if (fieldType == 'email') {
              email = value;
            }
            if (fieldType == 'password') {
              password = value;
            }
          });
        },
        cursorColor: Colors.purple.shade400,
        decoration: InputDecoration(
            focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.purple.shade400)),
            hintText:
                fieldType == 'email' ? 'Enter email...' : 'Enter password...',
            hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14)),
      ),
    );
  }

  /// Forgot password ///
  Widget forgotPassword() {
    return Align(
        alignment: Alignment.centerRight,
        child: Text(
          'Forgot password?',
          style: TextStyle(
              color: Colors.black54, fontWeight: FontWeight.w500, fontSize: 13),
        ));
  }

  /// Login and Register Button
  Widget loginRegisterButton() {
    return Padding(
      padding: EdgeInsets.only(top: 31, bottom: 21),
      child: MaterialButton(
          onPressed: email.isEmpty || password.isEmpty
              ? null
              : () async {
                  setState(() {});
                  showLoading = true;
                  if (loginScreenVisible) {
                    try {
                      print('get it now');
                      await AuthClass().signIn(email, password);
                      print('get it');
                    } on FirebaseAuthException catch (e) {
                      if (AuthClass().currentUser == null) {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            content: Text('Invalid email or password')));
                      }
                    }
                    setState(() {
                      showLoading = false;
                    });
                  }
                  if (!loginScreenVisible) {
                    try {
                      await AuthClass().register(email, password);
                    } on FirebaseAuthException catch (e) {
                      var res = await AuthClass()
                          .auth
                          .fetchSignInMethodsForEmail(email);
                      if (res.isNotEmpty)
                        ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('User already exists')));
                    }
                    setState(() {
                      showLoading = false;
                    });
                  }
                },
          padding: EdgeInsets.symmetric(vertical: 13),
          minWidth: double.infinity,
          color: Colors.purple.shade300,
          disabledColor: Colors.grey.shade300,
          textColor: Colors.white,
          child: showLoading
              ? SizedBox(
                  height: 20,
                  width: 20,
                  child: CircularProgressIndicator(
                    color: Colors.white,
                  ),
                )
              : Text(loginScreenVisible ? 'Login' : 'Register')),
    );
  }

     /// custom toggle button ///
  Widget toggleIconButton() {
    return InkWell(
      onTap: () {
        setState(() {
          loginScreenVisible = !loginScreenVisible;
        });
      },
      child: Container(
        padding: EdgeInsets.all(5),
        height: 50,
        width: 100,
        decoration: BoxDecoration(
            color: Colors.purple.shade100,
            borderRadius: BorderRadius.circular(100)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            loginScreenVisible
                ? toggleButtonText()
                : Expanded(
                    child: Center(
                      child: Text(
                        'Login',
                        style: TextStyle(color: Colors.white, fontSize: 11),
                      ),
                    ),
                  ),
            !loginScreenVisible
                ? toggleButtonText()
                : Expanded(
                    child: Center(
                      child: Text(
                        'Signup',
                        style: TextStyle(color: Colors.white, fontSize: 11),
                      ),
                    ),
                  ),
          ],
        ),
      ),
    );
  }

  Widget toggleButtonText() {
    return Expanded(
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
            shape: BoxShape.circle, color: Colors.purple.shade300),
        child: Text(
          loginScreenVisible ? 'Login' : 'Signup',
          style: TextStyle(color: Colors.white, fontSize: 11),
        ),
      ),
    );
  }
}

   //// home screen ///
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {

  final User? user = AuthClass().currentUser;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.purple,
        centerTitle: true,
        title: Text('Home Screen'),
        actions: [
          MaterialButton(
              onPressed: () async {
                await AuthClass().signOut();
              },
              child: Text('Signout', style: TextStyle(color: Colors.white)))
        ],
      ),
      body: Center(
        child: Container(
            padding: EdgeInsets.all(11),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                      blurRadius: 3,
                      spreadRadius: 1,
                      offset: Offset(3, 3),
                      color: Colors.grey.shade200)
                ]),
            child: Text(
                user!.email!.isEmpty ? 'No data' : user!.email.toString())),
      ),
    );
  }
}

    /// Firebase Operations ///
class AuthClass {
  final FirebaseAuth auth = FirebaseAuth.instance;
  User? get currentUser => auth.currentUser;
  Stream<User?> get authStateChanges => auth.authStateChanges();

  Future<void> signIn(email, password) async {
    await auth.signInWithEmailAndPassword(email: email, password: password);
  }

  Future<void> register(email, password) async {
    await auth.createUserWithEmailAndPassword(email: email, password: password);
  }

  Future<void> signOut() async {
    await auth.signOut();
  }
}

Conclusion

In conclusion, so this is how we can practically implement Flutter Firebase email authentication. Do feel free to share your valuable feedback in the comment section or email us. We’d love to read it.

We’d also love to see you visit our other tutorials on Flutter app development and Python programming. Thank you for reading this one.

Share this post:

Share on Twitter Share on Facebook Share on Pinterest Share on LinkedIn Share on WhatsApp
Flutter Firebase Tags:email authentication in flutter using firebase, example flutter auth firebase, example flutter authentication firebase, example flutter firebase auth, example flutter firebase auth email password, example flutter firebase email and password auth, example flutter firebase email and password authentication, example flutter firebase email authentication, example flutter firebase login auth, example flutter firebase login authentication, examples flutter firebase auth, examples flutter firebase email and password auth, examples flutter firebase email and password authentication, examples flutter firebase email authentication, firebase authentication in flutter, firebase authentication in flutter app, flutter auth, flutter auth app, flutter auth firebase, flutter auth firebase example, flutter authentication firebase, flutter authentication firebase example, flutter firebase auth, flutter firebase auth email password, flutter firebase auth email password example, flutter firebase auth example, flutter firebase auth examples, flutter firebase auth logout, flutter firebase auth register, flutter firebase auth registration, flutter firebase auth signout, flutter firebase auth signup, flutter firebase email and password auth, flutter firebase email and password auth example, flutter firebase email and password auth examples, flutter firebase email and password authentication, flutter firebase email and password authentication example, flutter firebase email and password authentication examples, flutter firebase email authentication, flutter firebase email authentication example, flutter firebase email authentication examples, flutter firebase login and registration, flutter firebase login auth, flutter firebase login auth example, flutter firebase login authentication, flutter firebase login authentication example, flutter firebase login tutorial, flutter firebase login with email and password

Post navigation

Previous Post: Flutter Firebase CRUD App [Create, Read, Update, Delete]
Next Post: How To Build Flutter ChatGPT App [Free Source Code]

Related Posts

flutter firebase crud app create read update delete data Flutter Firebase CRUD App [Create, Read, Update, Delete] Flutter Firebase
images showing flutter reset password using firebase and registration template and text showing flutter firebase change password Flutter Firebase Change Password – Practical Example Flutter Firebase

Leave a Reply Cancel reply

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

Latest Posts

  • Flutter Firebase Change Password – Practical Example
  • How To Build Flutter ChatGPT App [Free Source Code]
  • Flutter Firebase Email Authentication [Login, Signup, Logout]
  • Flutter Firebase CRUD App [Create, Read, Update, Delete]
  • [Solved] Flutter Pinch Zoom Image In ListView Builder
  • Flutter Contacts List [Display Data And Make A Call]
  • Flutter Reorderable Grid View Easy Explanation [Detailed Example]
  • Python Nested Dictionary [Explained With 6 Easy Examples]
  • Python Dictionary Keys Method [Easy Python Code Programs]
  • How To Use Python Dictionary FromKeys Method [Easy Examples]
  • Python Dictionary Clear Method [Explained With Examples]
  • How To Use Python Set Update Method [Python Code Examples]
  • How To Use Python Set Union Method [Easy Python Programs]
  • Python Set Symmetric Difference Update Method [Easy Examples]
  • How To Use Python Set Symmetric Difference Method
  • How To Use Python Set Pop Method [Easy Code Guide]
  • How To Use Python Set Issubset Method [Easy Python Examples]
  • How To Use Python Set IsDisjoint Method [Detailed Examples]
  • How To Use Python Set Intersection Update Method
  • How To Use Python Set Intersection [Easy Python Tutorial]
  • How To Properly Use Python Set Discard Method

Menu

  • Let Me Flutter – Home
  • Flutter App Development
  • Python Programming
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy

Categories

LATEST POSTS

  • Flutter Firebase Change Password – Practical Example
  • How To Build Flutter ChatGPT App [Free Source Code]
  • Flutter Firebase Email Authentication [Login, Signup, Logout]
  • Flutter Firebase CRUD App [Create, Read, Update, Delete]
  • [Solved] Flutter Pinch Zoom Image In ListView Builder

Copyright © 2023 Let Me Flutter.

Powered by PressBook Media WordPress theme