Flutter Course: 13.1 Implementing Conditional Statements and Login Functionality

Hello! In this tutorial, we will learn how to implement a login feature using conditional statements in Flutter. Flutter is a UI toolkit developed by Google that helps create applications easily across various platforms, including iOS and Android. Conditional statements are important elements that control the flow of programs. Let’s get started.

1. Overview of Conditional Statements

Conditional statements are used to evaluate whether a given condition is true or false to determine the flow of a program. In Flutter (or Dart language), we primarily use ‘if’, ‘else if’, ‘else’, and ‘switch’ statements to evaluate conditions.

        
        // Simple Example
        if (condition) {
            // Code executed when the condition is true
        } else {
            // Code executed when the condition is false
        }
        
    

By utilizing such conditional statements, we can provide a dynamic user experience based on user input. This allows us to implement the essential login screen feature in Flutter applications.

2. Designing the Login Screen

The login screen consists of a simple form that takes the user’s ID and password. In this tutorial, we will implement the login screen using text fields and a button.

2.1 Template Structure

        
        import 'package:flutter/material.dart';

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

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

        class LoginScreen extends StatefulWidget {
          @override
          _LoginScreenState createState() => _LoginScreenState();
        }

        class _LoginScreenState extends State {
          // Variables to store the ID and password
          String _username = '';
          String _password = '';

          @override
          Widget build(BuildContext context) {
            return Scaffold(
              appBar: AppBar(
                title: Text('Login Screen'),
              ),
              body: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    TextField(
                      decoration: InputDecoration(labelText: 'Username'),
                      onChanged: (value) {
                        _username = value;
                      },
                    ),
                    TextField(
                      decoration: InputDecoration(labelText: 'Password'),
                      obscureText: true,
                      onChanged: (value) {
                        _password = value;
                      },
                    ),
                    ElevatedButton(
                      onPressed: _login,
                      child: Text('Login'),
                    ),
                  ],
                ),
              ),
            );
          }
        }
        
    

3. Implementing the Login Functionality

When the login button is clicked, we need to implement functionality to check whether the login is successful based on certain conditions. At this point, we will set a predefined ID and password for verification.

        
        void _login() {
          // Predefined username and password
          const String predefinedUsername = 'user';
          const String predefinedPassword = 'password';

          // Use conditional statements to check login
          if (_username == predefinedUsername && _password == predefinedPassword) {
            // Login successful
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('Login Success'),
                  content: Text('Welcome!'),
                  actions: [
                    TextButton(
                      child: Text('OK'),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                );
              },
            );
          } else {
            // Login failed
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('Login Failed'),
                  content: Text('Incorrect username or password.'),
                  actions: [
                    TextButton(
                      child: Text('OK'),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                );
              },
            );
          }
        }
        
    

The above code checks whether the username and password entered by the user match the predefined information. If they match, a login success message is displayed in a popup; if they do not match, a login failure message is shown. We are controlling the flow using conditional statements.

4. Screen Transition on Login Success

Upon successful login, you can transition the user to another screen. For example, you can move to the main screen. Below is the code for transitioning the screen upon successful login.

        
        void _login() {
          const String predefinedUsername = 'user';
          const String predefinedPassword = 'password';

          if (_username == predefinedUsername && _password == predefinedPassword) {
            // On login success, navigate to the main screen
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => MainScreen()),
            );
          } else { /* ... (Handle login failure) ... */ }
        }

        class MainScreen extends StatelessWidget {
          @override
          Widget build(BuildContext context) {
            return Scaffold(
              appBar: AppBar(
                title: Text('Main Screen'),
              ),
              body: Center(
                child: Text('Welcome!'),
              ),
            );
          }
        }
        
    

In the above content, using `Navigator.pushReplacement` allows you to transition to a new screen upon login success and removes the previous screen from the stack, preventing you from returning to it.

5. Utilizing Conditional Statements Again

Conditional statements can be used to add various features based on user input, beyond just the login functionality. For example, consider providing a password recovery link when the user forgets their password.

        
        // Example of adding a password recovery button
        Column(
          children: [
            // Existing input fields...
            TextButton(
              onPressed: () {
                // Password recovery handling
                _forgotPassword();
              },
              child: Text('Forgot Password?'),
            ),
          ],
        );

        void _forgotPassword() {
          // Handle password recovery logic
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('Password Recovery'),
                content: Text('A reset link has been sent to the registered email.'),
                actions: [
                  TextButton(
                    child: Text('OK'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        }
        
    

6. Conclusion

In this tutorial, we learned how to implement a login functionality using Flutter and how to determine the success of the login using conditional statements. Properly utilizing conditional statements can significantly improve user experience and help in creating dynamic applications.

Now, you can implement your own login feature and add more functionalities. Through various exercises and practices, you can understand and implement complex logic using various conditional statements.

Thank you!