Create a responsive Login Screen for mobile, tablet and desktop

To create a responsive widget for mobile, tablet, and desktop devices in Flutter, you can use the MediaQuery class to get the screen size and orientation, and then use the LayoutBuilder widget to determine the layout based on the screen size.

login_screen_flutter


Here's an example:

responsive_helper.dart - Widget for mobile, tablet and Web.

import 'package:flutter/material.dart';

class ResponsiveWidget extends StatelessWidget {
  final Widget mobile;
  final Widget tablet;
  final Widget desktop;

  const ResponsiveWidget(
      {super.key,
      required this.mobile,
      required this.tablet,
      required this.desktop});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        var deviceWidth = MediaQuery.of(context).size.width;
        var deviceHeight = MediaQuery.of(context).size.height;
        var orientation = MediaQuery.of(context).orientation;

        if (deviceWidth < 600) {
          return mobile;
        } else if (deviceWidth >= 600 && deviceWidth < 900) {
          return tablet;
        } else {
          return desktop;
        }
      },
    );
  }
}

In this example, the MediaQuery class is used to get the screen size and orientation, and the LayoutBuilder widget is used to determine the layout based on the screen size. The layout is decided based on the screen width. The thresholds of 600 and 900 can be adjusted as needed.

You can then use this ResponsiveWidget by passing in different widgets for mobile, tablet, and desktop devices and wrapping it in your main widget.

We have created Login page using this Responsive widget:

This is a Flutter login form implementation with a responsive design. The form has two text fields for email and password, and a submit button. The design of the form adjusts based on the device's screen size (mobile, tablet, or desktop) using the ResponsiveWidget widget from the responsive_helper.dart file. The form validates the input fields and displays error messages if either of the fields is left empty. The form also saves the entered email and password when the submit button is pressed and prints them to the console.

import 'package:flutter/material.dart';
import 'package:responsive_design/widgets/responsive_helper.dart';

class LoginForm extends StatefulWidget {
  @override
  _LoginFormState createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  final _formKey = GlobalKey<FormState>();
  late String _email, _password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
      child: ResponsiveWidget(
        mobile: Expanded(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const logo(),
              Loginform(),
            ],
          ),
        ),
        tablet: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const logo(),
                  SingleChildScrollView(
                    child: SizedBox(
                        width: MediaQuery.of(context).size.width * 0.3,
                        child: Loginform()),
                  ),
                ],
              ),
            ),
          ],
        ),
        desktop: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const logo(),
                Container(
                    width: MediaQuery.of(context).size.width * 0.3,
                    child: Loginform()),
              ],
            ),
          ],
        ),
      ),
    ));
  }

  Form Loginform() {
    return Form(
      key: _formKey,
      child: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextFormField(
              decoration: const InputDecoration(labelText: 'Email'),
              validator: (value) {
                if (value!.isEmpty) {
                  return 'Please enter your email';
                }
                return null;
              },
              onSaved: (value) => _email = value!,
            ),
            TextFormField(
              decoration: const InputDecoration(labelText: 'Password'),
              obscureText: true,
              validator: (value) {
                if (value!.isEmpty) {
                  return 'Please enter your password';
                }
                return null;
              },
              onSaved: (value) => _password = value!,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  _formKey.currentState!.save();
                  print('Email: $_email, Password: $_password');
                }
              },
              child: const Text('Submit'),
            ),
          ],
        ),
      ),
    );
  }
}

class logo extends StatelessWidget {
  const logo({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Image.asset(
      'assets/images/logo.png',
      height: MediaQuery.of(context).size.height * 0.3,
      width: MediaQuery.of(context).size.height * 0.3,
      fit: BoxFit.cover,
    );
  }
}

Import statement: The code imports the required Flutter libraries and the responsive_helper.dart file which provides the ResponsiveWidget widget used for responsive design.

LoginForm class: The LoginForm class is a StatefulWidget that creates its own state class _LoginFormState.

_LoginFormState class: The _LoginFormState class extends the State widget and holds the logic for the form. It uses a GlobalKey called _formKey of type FormState to identify the form in the widget tree and access the form's state. It also holds two late variables, _email and _password, to store the entered values.

Build method: The build method returns a Scaffold widget that holds the form. The ResponsiveWidget widget from the responsive_helper.dart file is used to provide different layouts for the form based on the device's screen size (mobile, tablet, or desktop).

Loginform method: The Login form method returns a Form widget with two TextFormField widgets for email and password and a ElevatedButton widget for submit. The form has a validator method for each TextFormField to validate the input and an onSaved method to store the entered values in _email and _password.

Logo method: The logo class is a StatelessWidget that displays an image (logo) with a fixed height and width.

This is a high-level overview of the code. Let me comment below if you need any more clarification.

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

How to Make a Dynamic and Trending ListView with Flutter Widgets?

Understanding API integration with Getx State management