Logo

dev-resources.site

for different kinds of informations.

Flutter Custom Widget

Published at
4/16/2023
Categories
flutter
dart
widget
mobile
Author
devkishor8007
Categories
4 categories in total
flutter
open
dart
open
widget
open
mobile
open
Author
13 person written this
devkishor8007
open
Flutter Custom Widget

Image description

Namaste Everyone

I hope that you are doing well

Have you ever thought about making a custom widget to make your code more straightforward? If not, allow me to guide you through the process and show you how it can reduce redundancy in your code.

In this post, I will be sharing a custom widget that you can create. Custom widgets are great for making your code reusable and avoiding duplicate code.

Below is a snippet of a Login UI Page where you can see the repetitive code of TextField. However, the email and password TextField widgets have different controller names, obscureText, and hintText values.

// pages/login.page.dart
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  late final TextEditingController _email;
  late final TextEditingController _password;

  @override
  void initState() {
    super.initState();
    _email = TextEditingController();
    _password = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    _email.dispose();
    _password.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Login',
              style: TextStyle(
                fontSize: Theme.of(context).textTheme.headlineSmall!.fontSize,
              ),
            ),
            SizedBox(
              height: size.height * 0.01,
            ),
            TextFormField(
              controller: _email,
              obscureText: false,
              decoration: const InputDecoration(
                hintText: 'Enter your email..',
                hintStyle: TextStyle(
                  color: Colors.grey,
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.green,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(9),
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.green,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(9),
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.green,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(9),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: size.height * 0.01,
            ),
            TextFormField(
              controller: _password,
              obscureText: true,
              decoration: const InputDecoration(
                hintText: 'Enter your password..',
                hintStyle: TextStyle(
                  color: Colors.grey,
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.green,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(9),
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.green,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(9),
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.green,
                    width: 1.0,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(9),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: size.height * 0.025,
            ),
            ElevatedButton(
              onPressed: () {},
              child: const Text('Login'),
            ),
            SizedBox(
              height: size.height * 0.06,
            ),
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

After examining a lengthy code snippet of a Login UI Page, how do you feel?
Take a deep breath and don't worry.

Let me pause for a moment to think about how you could potentially simplify your code and design a custom widget for a TextFormField.

Don't worry if you're not sure, I'm here to share with you the steps you can take to create a custom widget.

// widgets/custom_textfield.dart
class CustomTextField extends StatelessWidget {
  final TextEditingController controller;
  final String hintText;
  final bool obscureText;
  const CustomTextField({
    super.key,
    required this.controller,
    required this.hintText,
    this.obscureText = false,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: TextFormField(
        controller: controller,
        obscureText: obscureText,
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: const TextStyle(
            color: Colors.grey,
          ),
          border: const OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.green,
              width: 1.0,
            ),
            borderRadius: BorderRadius.all(
              Radius.circular(9),
            ),
          ),
          focusedBorder: const OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.green,
              width: 1.0,
            ),
            borderRadius: BorderRadius.all(
              Radius.circular(9),
            ),
          ),
          errorBorder: const OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.red,
              width: 1.0,
            ),
            borderRadius: BorderRadius.all(
              Radius.circular(9),
            ),
          ),
          enabledBorder: const OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.green,
              width: 1.0,
            ),
            borderRadius: BorderRadius.all(
              Radius.circular(9),
            ),
          ),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

That's great! So you have created the CustomTextField widget. Do you know how to utilize the CustomTextField widget that you have created?

Also, regarding the snippet of CustomTextField widget, it's good to know that you can use it on any UI page wherever a form is needed.

// pages/login.page.dart
  CustomTextField(
                controller: _email,
                hintText: 'Enter your email..',
              ),
  CustomTextField(
                controller: _password,
                hintText: 'Enter your password..',
                obscureText: isVisible,
              ),
Enter fullscreen mode Exit fullscreen mode

Bonus
We can create the another custom widget of Text.

// widgets/custom_text.dart
class CustomText extends StatelessWidget {
  final String text;
  final double? fontSize;
  final Color? color;
  final FontWeight? fontWeight;
  const CustomText(
      {super.key,
      required this.text,
      this.fontSize,
      this.fontWeight,
      this.color});

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: TextStyle(
        fontSize: fontSize,
        fontWeight: fontWeight,
        color: color,
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Once you have created the CustomText widget, it can be utilized wherever it is required in your code.

// pages/homepage.dart
  CustomText(
       text: 'example',
       fontWeight: FontWeight.w800,
       fontSize: Theme.of(context)
            .textTheme
            .titleMedium!
            .fontSize,
          ),
Enter fullscreen mode Exit fullscreen mode

I hope you have found it helpful and enjoyable to learn how to create a custom widget in Flutter.
Thank you.

widget Article's
30 articles in total
Favicon
Forex Ticker Widget: Simplifying Forex Monitoring for Users
Favicon
Passing variables from the static page to the widget
Favicon
How to launch a React Native app from the Lock Screen on iPhone
Favicon
Free Currency HTML-Widgets
Favicon
Integrating Live Forex Quotes into Your Trading Platform Seamlessly
Favicon
Implement a Secure, Dynamic Domain Approval System for Embeddable Widgets in Ruby on Rails
Favicon
The Future of Professional Networking on LinkedIn: How Businesses Can Adapt and Stay Ahead
Favicon
Embed JS Widgets with Rails: A Step-by-Step Guide
Favicon
Create embeddable widgets in react for static pages
Favicon
FloatyNavBar: Elevate Your Flutter App's Navigation
Favicon
Web music player with html-css-javascript
Favicon
Free Currency HTML-Widgets
Favicon
Building an embeddable Widget
Favicon
Video, Live Chat & Help Center widget for the website
Favicon
100 Common Flutter widget list
Favicon
Back to basic : Flutter widget lifecycle
Favicon
FlutterFlow has introduced this fantastic new draggable widget!
Favicon
Bigcommerce Widget Migration
Favicon
Simple Digital Clock Widget
Favicon
Exploring Simple Widgets II: Autocomplete
Favicon
Improved Data Point Graph Widget for Cumulocity IoT
Favicon
Enhancing Cumulocity IoT Capabilities: Map-Based Widgets
Favicon
The Journey of a Widget: Understanding the Lifecycle in Flutter
Favicon
flutter row widget example
Favicon
Flutter Column Widget Example
Favicon
Common Widgets in Flutter
Favicon
Creating an iOS Currency Exchange Rate Widget: A Step-by-Step Guide
Favicon
Flutter Custom Widget
Favicon
How to embed appointment scheduling widget on your website?
Favicon
How to screenshot a widget in the flutter

Featured ones: