Flutter Course: The Meaning of State Management

Flutter is a UI framework created by Google that helps develop mobile, web, and desktop applications easily.
One of the advantages of Flutter is that it allows for efficient management of the application’s data flow through various state management solutions.
In this article, we will take a deep dive into the meaning and importance of state management in Flutter.

1. What is State Management?

State management refers to the process of tracking changes in data within an application and reflecting those changes in the UI.
There are various states, such as data input by users, data fetched from APIs, and data modified by the internal business logic of the application.
Effectively managing these states plays a crucial role in enhancing the performance and usability of Flutter applications.

2. What is State?

State refers to a collection of data that represents the current situation of the application. For example, whether a user is logged in, items in the shopping cart, and the state of UI animations can all be seen as a single ‘state’.
Each state plays an important role in determining the rendering of the UI, and it may be necessary to redraw the UI each time the state changes.

3. Why is State Management Important?

The reasons why state management is important are as follows:

  • Reduces Complexity: As applications grow larger, state management becomes more complex. If not managed properly, it can lead to data confusion.
  • Improves Code Readability: When the state management approach is clear, the code is easier to read and maintain.
  • Optimizes Performance: Appropriate state management can reduce unnecessary re-rendering, thereby improving the application’s performance.

4. State Management Techniques in Flutter

Flutter supports various state management techniques. Each technique has its unique advantages and disadvantages, and it is essential to choose the appropriate one based on the application’s requirements. The main techniques are as follows:

  • setState: An inline state management method that is the most basic form.
  • InheritedWidget: A base class provided by Flutter that can propagate state from parent widgets to child widgets.
  • Provider: Follows the pattern of object-oriented programming, enabling reactive state management.
  • BLoC: Business Logic Component, an architectural pattern that separates business logic from the UI.
  • Riverpod: An evolved version of Provider that offers a more intuitive and flexible API.
  • GetX: A lightweight state management method that provides lightweight performance optimization.

5. Detailed Explanation of Each Technique

5.1 setState

setState is the simplest way to manage state in Flutter. It is used when it is necessary to redraw the UI each time the state changes.
However, in complex applications, the use of setState can be inefficient and can decrease code readability.

5.2 InheritedWidget

InheritedWidget helps to easily propagate the state of a parent widget to its child widgets in Flutter’s widget tree structure.
By utilizing this, several widgets can access the same state, effectively reducing code duplication.

5.3 Provider

Provider is a state management pattern based on InheritedWidget, allowing state to be managed in an object-oriented manner.
Using Provider makes it easy to track changes in state and inject state throughout the code.

5.4 BLoC

The BLoC pattern separates state management and business logic, enhancing code readability and reusability.
This pattern is very helpful in effectively handling asynchronous data flows using streams.

5.5 Riverpod

Riverpod is based on Provider and offers looser coupling.
It allows for managing state for components individually without needing to follow all aspects of state management.

5.6 GetX

GetX is a lightweight state management pattern that offers more functionality with less code.
With a lightweight API, it boasts fast performance, making it suitable for large-scale applications.

6. Conclusion

State management is an essential element in Flutter application development.
Choosing and applying the appropriate state management technique contributes to improving the performance, readability, and maintainability of applications.
By starting from the basics and gradually learning various state management techniques, you can develop better applications.

In the upcoming lectures, we will delve deeper into various state management patterns.
Thank you for your interest!

Flutter Course – 16.6 Implementing Logout Functionality

In this course, we will learn in detail how to implement a logout feature in a Flutter application. The logout feature allows users to safely log out of their accounts, ensuring that the next user cannot see the information from the previous session. This enhances the security of user information.

1. Importance of the Logout Feature

The logout feature is a crucial element of the user experience. After users have logged in, they can perform specific actions, but it is necessary to safely terminate their session through logout. Additionally, when using multiple user accounts, the logout feature is essential. It helps users switch to a different account.

1.1 Protecting User Data

The logout feature protects session data left by previous users from affecting the next user. Without a logout feature, if someone logs in on a public device and does not log out, there is a risk of accessing personal information.

1.2 Improving User Experience

By providing a clear logout pathway, users can easily log out whenever they want. This is an important factor in enhancing the user experience.

2. Implementing Logout Feature in Flutter

Now let’s implement the logout feature in the Flutter project. You can build a simple yet effective logout system through the following steps.

2.1 Project Setup

First, you need to have a Flutter environment set up. Open your desired IDE and create a new Flutter project. Then, you should create a basic UI to make an app with login functionality. For example, you can modify the lib/main.dart file to set up the basic widget.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Login Screen')),
      body: Center(child: Text('Hello! Please log in.')),
    );
  }
}

2.2 State Management

To implement the logout feature, you need a way to manage the user’s login state. There are several methods, but you can use the Provider package. This allows for easy management of state throughout the application.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => Auth(),
      child: MyApp(),
    ),
  );
}

class Auth with ChangeNotifier {
  bool _isLoggedIn = false;

  bool get isLoggedIn => _isLoggedIn;

  void logIn() {
    _isLoggedIn = true;
    notifyListeners();
  }

  void logOut() {
    _isLoggedIn = false;
    notifyListeners();
  }
}

2.3 Creating Login and Logout Buttons

Now, you need to create login and logout buttons and add them to the UI. Each button should be connected to the state management class.

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final auth = Provider.of(context);
    
    return Scaffold(
      appBar: AppBar(title: Text('Home Screen')),
      body: Center(
        child: auth.isLoggedIn 
          ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('Welcome!'),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    auth.logOut();
                  },
                  child: Text('Logout'),
                ),
              ],
            )
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('You are not logged in.'),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    auth.logIn();
                  },
                  child: Text('Login'),
                ),
              ],
            ),
      ),
    );
  }
}

2.4 Integrating Logout Functionality into the Application

Now the logout function will be called when the button is clicked. This gives the user the ability to log out. You can refer to the code below to finalize your application.

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final auth = Provider.of(context);
    return Scaffold(
      appBar: AppBar(title: Text('Home Screen')),
      body: Center(
        child: auth.isLoggedIn 
          ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('Welcome!'),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    auth.logOut();
                  },
                  child: Text('Logout'),
                ),
              ],
            )
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('You are not logged in.'),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    auth.logIn();
                  },
                  child: Text('Login'),
                ),
              ],
            ),
      ),
    );
  }
}

3. Conclusion

This course taught you how to implement a logout feature in a Flutter application. The logout feature is important from a security perspective and plays a significant role in improving the user experience. Based on the topics covered in this course, try adding a logout feature to your projects as well.

Additionally, in a real environment, such logout features should be properly communicated with the server. Research methods for synchronizing logged-in user information with the server and requesting the server to log out to terminate the session. This can provide a better user experience and security.

4. References

Flutter Course, Implementing Login Functionality 16.5

In this article, we will explore in detail how to implement a login feature using the Flutter framework. The login feature is a core element of the user authentication process and is essential in many applications. Properly implementing the login feature plays a significant role in enhancing user experience and strengthening security.

1. Overview of Flutter and Login Feature

Flutter is a UI toolkit developed by Google, enabling the creation of beautiful and fast applications for both iOS and Android platforms from a single codebase. In particular, Flutter’s widget-based architecture helps to easily build user interfaces and effectively improve user experiences.

2. Reasons for Needing a Login Feature

  • Security: A login process is necessary to protect user data and prevent unauthorized access.
  • Personalization: When users log in, the user experience can be personalized, and persistent data storage becomes possible.
  • Data Management: The login feature allows administrators to efficiently collect and manage user data.

3. Project Setup

First, you need to check if the Flutter environment is installed. If the Flutter SDK is installed, you can create a new Flutter project using the command below.

flutter create login_example

Navigate to the project folder.

cd login_example

4. Adding Required Packages

To implement the login feature, you need to add the http package to manage HTTP requests. Additionally, you might need the provider package for form validation. Open the pubspec.yaml file and add the packages below:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3
  provider: ^5.0.0

Run the command below to apply the changes.

flutter pub get

5. Building Basic UI

Now, let’s build the basic UI for the login screen. Please write the following code in the lib/main.dart file.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Login Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  void _login() {
    // Login feature implementation is planned
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login Page'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: _emailController,
              decoration: InputDecoration(
                labelText: 'Email',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16.0),
            TextField(
              controller: _passwordController,
              decoration: InputDecoration(
                labelText: 'Password',
                border: OutlineInputBorder(),
              ),
              obscureText: true,
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: _login,
              child: Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}

6. Implementing Login Functionality

We will explore how to handle user login information in a mobile application and how to request that information from a server. Add the following code to the _login method:

import 'dart:convert';
import 'package:http/http.dart' as http;

void _login() async {
  String email = _emailController.text;
  String password = _passwordController.text;

  // Sending POST request to the server
  final response = await http.post(
    Uri.parse('https://example.com/api/login'),
    headers: {
      'Content-Type': 'application/json',
    },
    body: jsonEncode({
      'email': email,
      'password': password,
    }),
  );

  if (response.statusCode == 200) {
    // Login successful
    final data = jsonDecode(response.body);
    // Handle user information (e.g., save token)
    print('Login successful: ${data['token']}');
  } else {
    // Login failed
    print('Login failed: ${response.body}');
  }
}

7. Error Handling and User Feedback

If the login fails, provide an appropriate error message to the user. You can use the alert dialog box to display an error message. You can add the following code to show a message upon login failure:

if (response.statusCode != 200) {
  _showErrorDialog('Login failed. Please check your email or password.');
}

void _showErrorDialog(String message) {
  showDialog(
    context: context,
    builder: (ctx) => AlertDialog(
      title: Text('Error'),
      content: Text(message),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(ctx).pop(),
          child: Text('OK'),
        ),
      ],
    ),
  );
}

8. Adding Form Validation

It is advisable to add field validation to ensure that users enter valid email and password. You can validate input using Flutter’s Form and TextFormField widgets.

final _formKey = GlobalKey();

@override
Widget build(BuildContext context) {
  return Form(
    key: _formKey,
    child: Column(
      ...
      children: [
        TextFormField(
          controller: _emailController,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please enter your email.';
            }
            return null;
          },
          ...
        ),
        TextFormField(
          controller: _passwordController,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please enter your password.';
            }
            return null;
          },
          ...
        ),
        ElevatedButton(
          onPressed: () {
            if (_formKey.currentState!.validate()) {
              _login();
            }
          },
          child: Text('Login'),
        ),
      ],
    ),
  );
}

9. Session Management

To manage the user’s session after login, you can store the token of the logged-in user in local storage. Using the shared_preferences package allows for easy storage. Implement session management as follows:

import 'package:shared_preferences/shared_preferences.dart';

void _login() async {
  // ... existing code omitted ...
  
  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    // Save token
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('token', data['token']);
    print('Login successful: ${data['token']}');
  }

10. Implementing Logout Functionality

Add a logout feature so that users can log out. During logout, end the session and remove the stored token.

void _logout() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.remove('token');
  print('Logged out successfully.');
}

11. Additional Security Considerations

When implementing the login feature, consider the following security principles:

  • HTTPS: Login requests should always use HTTPS protocol for encryption.
  • Password Storage: User passwords should be stored encrypted and should not be exposed directly.
  • Two-Factor Authentication: Consider implementing Two-Factor Authentication (MFA) for additional security.

12. Conclusion

In this tutorial, we explored in detail how to implement a login feature using Flutter. User authentication is an important part of applications and should be designed with security and user experience in mind. Built on the login feature, we hope to create applications that manage user data securely and efficiently.

We will cover more Flutter-related topics in future tutorials, so please stay tuned. Thank you!

Flutter Course: Creating a Member Registration Page and Implementing Sign-Up Functionality

Hello! Today we will learn how to create a sign-up page using Flutter and implement the sign-up functionality. User authentication is a very important aspect of mobile applications, and the sign-up feature is the starting point. In this tutorial, we will create a form that accepts the user’s email, password, and additional information, and learn how to connect it with Firebase Authentication to create a valid account.

1. Prerequisites

First, you need to prepare the following for learning:

  • Flutter SDK must be installed. Refer to the official website for installation instructions.
  • A Firebase account for the relevant project is needed. Sign up on the Firebase console and create a project.
  • You need Android Studio or another code editor.
  • You should install the related packages for Flutter. Add the necessary Flutter dependencies for Firebase and HTTP requests.

2. Firebase Project Setup

To use the sign-up functionality with Firebase, you need to set up a Firebase project. Follow the steps below to set it up.

  1. Log in to the Firebase console and create a new project.
  2. Go to the ‘Authentication’ menu and enable the email/password option under ‘Sign-in methods’.
  3. Register the Android/iOS app through ‘App registration’ and download the necessary Google services configuration file.

3. Creating a Flutter Project

To create a new Flutter project, enter the following command in your terminal:

flutter create sign_up_app

After moving to the project folder, run the following commands to install the required packages:

cd sign_up_app
flutter pub add firebase_core
flutter pub add firebase_auth

4. Initializing Firebase

Now you need to initialize Firebase to use it in your Flutter app. Open the lib/main.dart file and add the following code:

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

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

class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: SignUpPage(), // Set to point to sign-up page
        );
    }
}

5. Designing the Sign-Up Page UI

The sign-up page consists of a form where users can enter their email and password. Add the following code to design the sign-up page UI.

class SignUpPage extends StatefulWidget {
    @override
    _SignUpPageState createState() => _SignUpPageState();
}

class _SignUpPageState extends State {
    final _emailController = TextEditingController();
    final _passwordController = TextEditingController();

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
                title: Text('Sign Up'),
            ),
            body: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                    children: [
                        TextField(
                            controller: _emailController,
                            decoration: InputDecoration(labelText: 'Email'),
                        ),
                        TextField(
                            controller: _passwordController,
                            decoration: InputDecoration(labelText: 'Password'),
                            obscureText: true,
                        ),
                        SizedBox(height: 20),
                        ElevatedButton(
                            onPressed: _signUp,
                            child: Text('Sign Up'),
                        ),
                    ],
                ),
            ),
        );
    }

    void _signUp() {
        // Implement sign-up logic here.
    }
}

6. Implementing Sign-Up Functionality

Implement the logic to create an account by processing the email and password entered by the user through Firebase Authentication. Add the following code to the _signUp method:

void _signUp() async {
    final email = _emailController.text;
    final password = _passwordController.text;
    
    try {
        UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
            email: email,
            password: password,
        );
        // You can perform additional tasks after successful sign-up.
        print("Sign-up successful: ${userCredential.user.uid}");
    } catch (e) {
        print("Sign-up failed: $e");
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Sign-up failed')));
    }
}

7. Error Handling and Validation

It is necessary to handle errors for the sign-up feature in case the user inputs incorrect information. You can check whether the entered email format is correct and the minimum length of the password to create a more robust feature.

void _signUp() async {
    final email = _emailController.text;
    final password = _passwordController.text;  
    
    if (!_isEmailValid(email) || !_isPasswordValid(password)) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Invalid input')));
        return;
    }

    try {
        UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
            email: email,
            password: password,
        );
        print("Sign-up successful: ${userCredential.user.uid}");
        // You can navigate to the next page or perform other actions.
    } catch (e) {
        print("Sign-up failed: $e");
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Sign-up failed: ${e.toString()}')));
    }
}

bool _isEmailValid(String email) {
    return RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$').hasMatch(email);
}

bool _isPasswordValid(String password) {
    return password.length >= 6;
}

8. User Feedback

After completing the sign-up functionality, it’s good to consider providing the user with success or failure messages. You can use the SnackBar used in the code above to provide simple feedback.

9. Conclusion and Next Steps

Through this tutorial, you learned how to create a simple sign-up page using Flutter and how to create user accounts through Firebase Authentication. Now you can incorporate these features into your application to allow more users to access it.

As the next step, it would be good to learn more advanced features such as implementing user login functionality or integrating social login. Thank you!

If you found this article helpful, please like and comment!

Flutter Course: 16.3 Installing Firebase Auth Package and Setting Up Email Authentication

Hello, Flutter developers! In this tutorial, we will explore in detail how to set up user authentication via Email using Firebase. Firebase offers a variety of services including databases, hosting, storage, and particularly Firebase Auth, which is very useful for handling user authentication. In this tutorial, we will guide you step-by-step on how to install the Firebase Auth package and set up email authentication.

1. Create a Firebase Project

To use Firebase, you first need to create a project in the Firebase console. Follow the steps below to create a project.

  1. Access the Firebase console.
  2. Click the ‘Add Project’ button in the top right corner.
  3. Enter the project name, select the Google Analytics settings, and then click ‘Create Project’.

2. Set up Firebase Auth

Once the project is created, you need to set up Firebase Auth.

  1. Click on ‘Authentication’ in the left menu.
  2. Navigate to the ‘Sign-in method’ tab.
  3. Find and enable the Email/Password sign-in option.

3. Create a Flutter Project

Now, let’s create a Flutter project. Use the command below to create a new Flutter project.

flutter create firebase_auth_example

Navigate to the project directory.

cd firebase_auth_example

4. Install Firebase Core and Auth Packages

You need to add the necessary packages to use Firebase in Flutter. Open the ‘pubspec.yaml’ file and add the following dependencies.

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.0.0
  firebase_auth: ^5.0.0

Now, enter the command below to install the packages.

flutter pub get

5. Initialize Firebase

After installing the packages, you need to initialize Firebase. Open the ‘main.dart’ file and add the following code.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Auth Example',
      home: HomeScreen(),
    );
  }
}

6. Create Login UI

Let’s build a login screen for email authentication. Add the ‘HomeScreen’ widget and include fields for email and password input as well as a login button.

import 'package:firebase_auth/firebase_auth.dart';

// ...

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  void signIn(String email, String password) async {
    try {
      UserCredential userCredential = await _auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      print('User signed in: ${userCredential.user}');
    } on FirebaseAuthException catch (e) {
      print('Failed to sign in: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _emailController,
              decoration: InputDecoration(labelText: 'Email'),
            ),
            TextField(
              controller: _passwordController,
              decoration: InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                signIn(_emailController.text, _passwordController.text);
              },
              child: Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}

7. Request Email Verification

After signing in, the user can request email verification. Add the code as below.

void sendVerificationEmail(User user) async {
  if (!user.emailVerified) {
    await user.sendEmailVerification();
    print('Verification email sent to ${user.email}');
  }
}

// Add this at the end of the signIn method.
if (userCredential.user != null) {
  sendVerificationEmail(userCredential.user!);
}

8. Check Email Verification

Add logic to check if the user has verified their email. You can verify whether the user checked their email after logging in.

void checkEmailVerification() async {
  User? user = _auth.currentUser;
  await user?.reload();
  user = _auth.currentUser;
  if (user != null && user.emailVerified) {
    print('Email verified!');
    // Logic to navigate as a verified user can be added.
  } else {
    print('Email not verified yet.');
  }
}

// Add at the end of the signIn method.
checkEmailVerification();

9. Complete Code

Finally, the complete main.dart code is as follows.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Auth Example',
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  void signIn(String email, String password) async {
    try {
      UserCredential userCredential = await _auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      sendVerificationEmail(userCredential.user!);
      checkEmailVerification();
    } on FirebaseAuthException catch (e) {
      print('Failed to sign in: $e');
    }
  }

  void sendVerificationEmail(User user) async {
    if (!user.emailVerified) {
      await user.sendEmailVerification();
      print('Verification email sent to ${user.email}');
    }
  }

  void checkEmailVerification() async {
    User? user = _auth.currentUser;
    await user?.reload();
    user = _auth.currentUser;
    if (user != null && user.emailVerified) {
      print('Email verified!');
    } else {
      print('Email not verified yet.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _emailController,
              decoration: InputDecoration(labelText: 'Email'),
            ),
            TextField(
              controller: _passwordController,
              decoration: InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                signIn(_emailController.text, _passwordController.text);
              },
              child: Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}

10. Conclusion

Now you have learned how to set up email authentication using Flutter and Firebase. Requesting email verification is an important feature to enhance user experience. Please utilize this feature for additional security. In the next tutorial, we will cover how to implement social login. Thank you!