How to Create Custom Widgets in Flutter

Tutorial 5 of 5

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!