top of page

Mobile App Development with Flutter & Dart: Create a a login page with flutter including validation

  • codeagle
  • Aug 18, 2024
  • 2 min read

Mobile development is one of the trending aspects in Software Development. Creating a basic login screen in Flutter involves setting up a form with text fields for the username/email and password, along with a button to submit the form. Below is a simple example:


ree

Step 1: Set Up a New Flutter Project

If you haven't created a Flutter project yet, start by creating one:

flutter create login_example
cd login_example

Step 2: Modify pubspec.yaml (Optional)

Ensure you have any necessary dependencies. For a basic login, you don’t need to add any extra dependencies, but if you plan to add form validation or state management, you might consider adding packages like provider or flutter_bloc.

Step 3: Create the Login Screen

Open the lib/main.dart file and replace its contents with the following code:

import 'package:flutter/material.dart';

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

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

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

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  String _email = '';
  String _password = '';

  void _submit() {
    if (_formKey.currentState?.validate() ?? false) {
      _formKey.currentState?.save();
      // Perform login logic here
      print('Email: $_email');
      print('Password: $_password');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your email';
                  }
                  if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
                    return 'Please enter a valid email address';
                  }
                  return null;
                },
                onSaved: (value) {
                  _email = value ?? '';
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your password';
                  }
                  return null;
                },
                onSaved: (value) {
                  _password = value ?? '';
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _submit,
                child: Text('Login'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Step 4: Run the App

You can run the app on your device or simulator with:

flutter run

Explanation:

  • MyApp: The root of the application. It sets up the theme and the home screen.

  • LoginScreen: The main screen where the login form is displayed.

  • _LoginScreenState: The state class where the logic resides. It handles form validation and submission.

  • Form: A widget that groups input fields and allows you to validate and save their values.

  • TextFormField: Used for email and password input. Includes validation logic.

  • ElevatedButton: Triggers the form submission when pressed.

This code sets up a basic login form with validation for both the email and password fields. You can expand this by connecting it to a backend service for authentication or adding more features like error handling and state management.

Comments


Thank you for being a Codeagle Reader :)
  • Grey Twitter Icon
bottom of page