Flutter / Flutter Widgets

How to Create Custom Widgets in Flutter

This tutorial teaches you how to create your own custom widgets in Flutter. This is a powerful technique that allows you to write reusable and modular code.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explore the concept of Widgets, the basic building blocks for UI in Flutter.

Creating Custom Widgets in Flutter

1. Introduction

In this tutorial, you will learn how to create your own custom widgets in Flutter, a powerful technique that enables you to write reusable and modular code. By the end of this tutorial, you'll understand how to define and implement custom widgets and how to use them in your Flutter applications.

Prerequisites

  1. Basic understanding of Dart programming language
  2. Familiarity with Flutter SDK and widget structure

2. Step-by-Step Guide

In Flutter, everything is a widget. You can think of widgets as the building blocks for your Flutter applications. There are two types of widgets in Flutter: Stateless and Stateful. Stateless widgets are immutable, their properties are final, while Stateful widgets have mutable state.

Creating a Stateless Widget

To create a custom Stateless widget, you need to:

  1. Create a new class that extends StatelessWidget.
  2. Override the build method.

Here is an example:

class CustomText extends StatelessWidget {
  final String text;

  CustomText(this.text);

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

In this example, CustomText is a StatelessWidget that takes a String parameter and renders it as a Text widget with a specific style.

Creating a Stateful Widget

Creating a Stateful widget involves a bit more work. You need to:

  1. Create a new class that extends StatefulWidget.
  2. Create a separate class that extends State.
  3. In the State class, override the build method.

Here is an example:

class CustomButton extends StatefulWidget {
  final String buttonText;

  CustomButton({this.buttonText});

  @override
  _CustomButtonState createState() => _CustomButtonState();
}

class _CustomButtonState extends State<CustomButton> {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text(widget.buttonText),
      onPressed: () {
        print('Button pressed');
      },
    );
  }
}

In this example, CustomButton is a StatefulWidget that takes a String parameter and renders a RaisedButton with the provided text.

3. Code Examples

Example 1: Stateless Widget

This is a simple example of a custom Stateless widget that displays a text message:

class CustomText extends StatelessWidget {
  final String message;

  CustomText(this.message);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.blue,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Text(
        message,
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
    );
  }
}

Example 2: Stateful Widget

This custom Stateful widget is a counter. Clicking the button increments the counter:

class CustomCounter extends StatefulWidget {
  @override
  _CustomCounterState createState() => _CustomCounterState();
}

class _CustomCounterState extends State<CustomCounter> {
  int _count = 0;

  void _incrementCounter() {
    setState(() {
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text(
          'Count: $_count',
          style: TextStyle(fontSize: 24),
        ),
        RaisedButton(
          onPressed: _incrementCounter,
          child: Text('Increment'),
        ),
      ],
    );
  }
}

4. Summary

In this tutorial, you learned how to create custom widgets in Flutter, including both Stateless and Stateful widgets. You learned the importance of widgets in Flutter and how to use them to build reusable and modular code. The next step in your learning journey could be to explore more complex Stateful widgets and how to manage state in a larger Flutter application.

5. Practice Exercises

  1. Create a custom Stateless widget that displays an image from a URL passed to it as a parameter.
  2. Create a custom Stateful widget that toggles between two colors when tapped.
  3. Extend the CustomCounter widget to include decrement and reset buttons.

Solutions

  1. Custom Stateless Widget
class CustomImage extends StatelessWidget {
  final String imageUrl;

  CustomImage(this.imageUrl);

  @override
  Widget build(BuildContext context) {
    return Image.network(imageUrl);
  }
}
  1. Custom Stateful Widget
class ColorToggle extends StatefulWidget {
  @override
  _ColorToggleState createState() => _ColorToggleState();
}

class _ColorToggleState extends State<ColorToggle> {
  bool _isBlue = true;

  void _toggleColor() {
    setState(() {
      _isBlue = !_isBlue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _toggleColor,
      child: Container(
        color: _isBlue ? Colors.blue : Colors.red,
      ),
    );
  }
}
  1. Extended CustomCounter Widget
class CustomCounter extends StatefulWidget {
  @override
  _CustomCounterState createState() => _CustomCounterState();
}

class _CustomCounterState extends State<CustomCounter> {
  int _count = 0;

  void _incrementCounter() {
    setState(() {
      _count++;
    });
  }

  void _decrementCounter() {
    setState(() {
      _count--;
    });
  }

  void _resetCounter() {
    setState(() {
      _count = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text(
          'Count: $_count',
          style: TextStyle(fontSize: 24),
        ),
        RaisedButton(
          onPressed: _incrementCounter,
          child: Text('Increment'),
        ),
        RaisedButton(
          onPressed: _decrementCounter,
          child: Text('Decrement'),
        ),
        RaisedButton(
          onPressed: _resetCounter,
          child: Text('Reset'),
        ),
      ],
    );
  }
}

Keep practicing and exploring more functionalities with custom widgets. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help