Open In App

How to Build a Simple Login App with Flutter?

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

To prevent unauthorized access to personal information, it is a good practice to authenticate users before granting access to websites, mobile applications, and computer applications, after then register and then login. In this article, we are going to explain how to build a Design Login page user interface. We have used the TextField widget, for user input as Username/Email,  and Password. And below of password TextField to create the option Forget Password. Button widget, to show action. Also, we have used Image to set the logo for your Organization/Institute/Company Login page design. A sample video is given below to get an idea about what we will do in this article.

Required Tools

To build this app, you need the following items installed on your machine:

  1. Visual Studio Code (One of Flutter’s recommended IDEs).
  2. Android Emulator / iOS Simulator / Original device.
  3. Flutter Installed (I would recommend following this guide to install it if you don’t have it already)
  4. Flutter plugin for VS Code (Recommended Guide).

How to Create the Project?

  • Open Visual Studio Code from that directory.
  • Open the command palette by pressing CTRL + SHIFT + P and type Flutter. Choose Flutter: New Project from the listed options.
  • Select Application from the next list.
  • It’ll ask you to Select the target folder to create the project. By default, it’ll be in the same folder where you opened VS Code. Type your app name in the text input and hit Enter. I’m naming mine loginapp, but you can type any name you wish.             

Note: Here, the flutter-logo.png file is copied into the asset/images folder in this flutter application and written into the pubspec.yaml file to get it in our code.

# To add assets to your application, add an assets section, like this:
assets:
- asset/images/

After adding asset run Packages get command to get a result.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package in the pubspec.yaml File

First of all import material.dart file.

import 'package:flutter/material.dart';

Then import login.dart file.

import 'package:flutter_application_3/screen/register.dart';

Then execute a main function.

void main() => runApp(MaterialApp)

Then add initialRoute to the login page.

initialRoute: '/',
    routes: {'/': (context) => Login()},

Here is the code to refer to the main.dart file:

Dart




import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_application_3/screen/login.dart';
  
void main() => runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      initialRoute: '/',
      routes: {'/': (context) => Login()},
));


Validation:

  • If you want to apply validation, then you can use it by going to the pubspec.yaml file and setting its dependency.
  • In the below code, we have mentioned the code of validation in the login file.
  • If you use validation, you have to use the package with validation in the Login file and set the dependency as well.
import 'package:form_field_validator/form_field_validator.dart';

Step 3: Second Page Create a login.dart file

  • First of all, we create second page login.dart file name.
  • Then import material.dart file.
import 'package:flutter/material.dart';

Note: If you use validation, you have to use the package with validation in the login file and set the dependency as well.

import 'package:form_field_validator/form_field_validator.dart';
  • Then we create a Stateful widget.
  • Set Scaffold’s AppBar property as follows to make a heading for our application.
  • For this UI, all widgets are placed inside the Column widget, into the Scaffold body. The first child of Column is the Container widget which holds the Image widget as its child.
  • Here, the flutter-logo.png file is copied into the assets/images folder in this flutter application and written into the pubspec.yaml file to get it in our code.
  • Then, for Username or Email and Password use the TextField widget. TextField widget is an input widget that helps you to take input from the user.

Example of Email Textfield and use validation:

 Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextFormField(
                      validator: MultiValidator([
                        RequiredValidator(errorText: ‘Enter email address’),
                        EmailValidator(
                            errorText: ‘Please correct email filled’),
                      ]),
                      decoration: InputDecoration(
                          hintText: ‘Email’,
                          labelText: ‘Email’,
                          prefixIcon: Icon(
                            Icons.email,
                            color: Colors.lightBlue,
                          ),
                          errorStyle: TextStyle(fontSize: 18.0),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.red),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(9.0)))),
                    ),
                  ),

Example of Password Textfield and use validation:

Padding(
                           padding: const EdgeInsets.all(12.0),
                           child: TextFormField(
                             validator: MultiValidator([
                               RequiredValidator(
                                   errorText: ‘Please enter Password’),
                               MinLengthValidator(8,
                                   errorText:
                                       ‘Password must be atlist 8 digit’),
                               PatternValidator(r'(?=.*?[#!@$%^&*-])’,
                                   errorText:
                                       ‘Password must be atlist one special character’)
                             ]),
                             decoration: InputDecoration(
                               hintText: ‘Password’,
                               labelText: ‘Password’,
                               prefixIcon: Icon(
                                 Icons.key,
                                 color: Colors.green,
                               ),
                               errorStyle: TextStyle(fontSize: 18.0),
                               border: OutlineInputBorder(
                                   borderSide: BorderSide(color: Colors.red),
                                   borderRadius:
                                       BorderRadius.all(Radius.circular(9.0))),
                             ),
                           ),
                         ),

Example of Login Button:

 Padding(
                           padding: const EdgeInsets.all(28.0),
                           child: Container(
                             child: RaisedButton(
                               child: Text(
                                 ‘Login’,
                                 style: TextStyle(
                                     color: Colors.white, fontSize: 22),
                               ),
                               onPressed: () {
                                 if (_formkey.currentState!.validate()) {
                                   print(‘form submiitted’);
                                 }
                               },
                               shape: RoundedRectangleBorder(
                                   borderRadius: BorderRadius.circular(30)),
                               color: Colors.blue,
                             ),
                             width: MediaQuery.of(context).size.width,
                             height: 50,
                           ),
                         ),

Here, the Padding widget helps you to give some space all around your TextField widget. Here we can wrap the Text widget with GestureDetector widget which gives us onTap() to navigate. OR create this button same as Forgot Password button to get the OnPressed() event.

Here is the full code to refer to login.dart file

Dart




import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:form_field_validator/form_field_validator.dart';
  
class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);
  
  @override
  State<Login> createState() => _LoginState();
}
  
class _LoginState extends State<Login> {
  Map userData = {};
  final _formkey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 30.0),
              child: Center(
                child: Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      border: Border.all(color: Colors.blueGrey)),
                  child: Image.asset('assets/logo.png'),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Form(
                    key: _formkey,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Padding(
                              padding: const EdgeInsets.all(12.0),
                              child: TextFormField(
                                  validator: MultiValidator([
                                    RequiredValidator(
                                        errorText: 'Enter email address'),
                                    EmailValidator(
                                        errorText:
                                            'Please correct email filled'),
                                  ]),
                                  decoration: InputDecoration(
                                      hintText: 'Email',
                                      labelText: 'Email',
                                      prefixIcon: Icon(
                                        Icons.email,
                                        //color: Colors.green,
                                      ),
                                      errorStyle: TextStyle(fontSize: 18.0),
                                      border: OutlineInputBorder(
                                          borderSide:
                                              BorderSide(color: Colors.red),
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(9.0)))))),
                          Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: TextFormField(
                              validator: MultiValidator([
                                RequiredValidator(
                                    errorText: 'Please enter Password'),
                                MinLengthValidator(8,
                                    errorText:
                                        'Password must be atlist 8 digit'),
                                PatternValidator(r'(?=.*?[#!@$%^&*-])',
                                    errorText:
                                        'Password must be atlist one special character')
                              ]),
                              decoration: InputDecoration(
                                hintText: 'Password',
                                labelText: 'Password',
                                prefixIcon: Icon(
                                  Icons.key,
                                  color: Colors.green,
                                ),
                                errorStyle: TextStyle(fontSize: 18.0),
                                border: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.red),
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(9.0))),
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.fromLTRB(180, 0, 0, 0),
                            child: Text('Forget Password!'),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(28.0),
                            child: Container(
                              child: RaisedButton(
                                child: Text(
                                  'Login',
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 22),
                                ),
                                onPressed: () {
                                  if (_formkey.currentState!.validate()) {
                                    print('form submiitted');
                                  }
                                },
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(30)),
                                color: Colors.blue,
                              ),
                              width: MediaQuery.of(context).size.width,
                              height: 50,
                            ),
                          ),
                          Center(
                            child: Padding(
                              padding: EdgeInsets.fromLTRB(0, 30, 0, 0),
                              child: Center(
                                child: Text(
                                  'Or Sign In Using!',
                                  style: TextStyle(
                                      fontSize: 18, color: Colors.black),
                                ),
                              ),
                            ),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Padding(
                                padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
                                child: Row(
                                  children: [
                                    Container(
                                        height: 40,
                                        width: 40,
                                        child: Image.asset(
                                          'assets/social.jpg',
                                          fit: BoxFit.cover,
                                        )),
                                    Container(
                                      height: 70,
                                      width: 70,
                                      child: Image.asset(
                                        'assets/vishal.png',
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                    Container(
                                      height: 40,
                                      width: 40,
                                      child: Image.asset(
                                        'assets/google.png',
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          Center(
                            child: Container(
                              padding: EdgeInsets.only(top: 50),
                              child: Text(
                                'SIGN UP!',
                                style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.lightBlue,
                                ),
                              ),
                            ),
                          )
                        ]),
                  )),
            ),
          ],
        ),
      ),
    );
  }
}


  • The Scaffold is a widget in Flutter used to implement the basic material design visual layout structure. Assume the widget is a simple UI component.
  • We’re setting the title passed as a parameter to this class. We can access the parameters using the widget object. So, it goes like a widget.{key_name}.
  • If you want to access the title property, then it’ll be a widget.title. This is similar to passing props in React.
  • The next section is the body. As we’re building a simple login app, we need a form to be filled out by the user to authenticate. We’re setting the unique key which we created above to this form. The Form accepts a child. It can accept only one component.
  • We are creating a layout with horizontal padding of 15px and vertical padding of 16px. This Padding widget also accepts only one child.
  • The column is a widget in Flutter that is used to display its children in a vertical array. We set crossAxisAlignment to horizontally center the contents of the Column widget.
  • As we saw, the Column widget displays its children in a vertical array. We can pass multiple widgets on its children’s property.
  • The first item we want to display in the UI is an input box to get the email address of a user. So, we used the TextFormField widget and set the controller to email Controller.
  • In order to get the floating text, we need to use the decoration option which asks for the type of border and the labelText of the input.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads