How do I add a checkbox in flutter?

We can use several input components in flutter. Checkbox is one of them. Moreover, we can add a checkbox quite easily.

However, we need to understand the main concept behind any checkbox. Firstly, one of the ancestor of any checkbox should be a Material widget.

Secondly, since checkbox is a type of input component, it always holds a Boolean value.

While we check a checkbox or mark it with a tick sign, that means yes. If we don’t, it means no. However, there is another value. Null.

A checkbox can display null also.

A material design checkbox doesn’t maintain any state.

Then what happens when a user marks a checkbox with a tick sign?

Only when a user checks or marks a checkbox, the state of checkbox changes, and the widget calls the onChanged callback.

Each time, when a widget uses a checkbox, will listen to the onChanged callback and rebuilds the checkbox with a new value. Following that an update takes place and that changes the visual appearance of the checkbox.

Enough talking, let’s see a snippet of code that displays one checkbox. Let’s suppose, a checkbox widget is the child of a Material widget and it will use the checkbox.

class CheckBoxExample extends StatelessWidget {
  const CheckBoxExample({Key? key}) : super(key: key);

  static const String _title = 'CheckBox Example';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: CheckBoxWidget(),
        ),
      ),
    );
  }
}

The first condition is CheckBoxWidget must be a stateful widget. So that when the value of checkbox changes the onChanged callback will be applied to the value, which can be yes.

Suppose, the callback is null. In that case, the checkbox will not respond to any input gestures. However, if we tap the checkbox, the callback cycle changes from no to yes, or null.

Let us see the next part of the code.

class CheckBoxWidget extends StatefulWidget {
  const CheckBoxWidget({Key? key}) : super(key: key);

  @override
  State<CheckBoxWidget> createState() => _CheckBoxWidgetState();
}

class _CheckBoxWidgetState extends State<CheckBoxWidget> {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    Color changeColor(Set<MaterialState> states) {
      const Set<MaterialState> interactiveStates = <MaterialState>{
        MaterialState.pressed,
        MaterialState.hovered,
        MaterialState.focused,
      };
      if (states.any(interactiveStates.contains)) {
        return Colors.blue;
      }
      return Colors.red;
    }

    return Checkbox(
      checkColor: Colors.white,
      fillColor: MaterialStateProperty.resolveWith(changeColor),
      value: isChecked,
      onChanged: (bool? value) {
        setState(() {
          isChecked = value!;
        });
      },
    );
  }
}

The Checkbox onChanged property now updates the state of the parent StatefulWidget using the State.setState method.

As a result, the parent StatefulWidget gets rebuilt, and the color of the checkbox changes.

Checkbox example without switch
Checkbox example without switch

In the next example we’ll see another example of checkbox along with the Switch widget.

How do you change the check box color in flutter?

There are several options to change the color of a checkbox.

Usually, when we see a checkbox on the screen, it displays a square box with white space. When a user hover over the checkbox, it may change its color. To clarify, we can revisit the previous code where we’ve used Set<MaterialState>.

With the help of MaterialState and MaterilaStateProperty we can manage that change in color as state changes.

But there is another easier method to change the color of checkbox.

Let’s see the screenshot first.

Checkbox clicked and color changes
Checkbox clicked and color changes

In the above image when we tap the checkbox, the checkbox color changes to blue, and the color of Switch changes to red.

How did that happen?

Very simple.

Both checkbox and switch widgets have a property called activeColor. We can mention the color constant value there so that each time user tap any one of them, the concerned widgets change to that activeColor.

Let us see the respective code snippet.

body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Checkbox(
                value: _value,
                onChanged: (bool? value) {
                  setState(
                    () {
                      _value = value!;
                    },
                  );
                },
                activeColor: Colors.blue,
                tristate: true,
              ),
              Switch.adaptive(
                value: _value,
                activeColor: Colors.redAccent,
                activeTrackColor: Colors.redAccent,
                onChanged: (bool? value) {
                  setState(
                    () {
                      _value = value!;
                    },
                  );
                },
              ),
            ],
          ),
        ),
// code is incomplete for brevity. Please visit the GitHub repository to get the full code snippet.

To sum up, in this article we’ve learned how to use checkbox in flutter. However, besides this compact version of checkbox, we have CheckboxListTile widget, in which we can describe the header and subtitle using the respective properties.

In the next articles, we’ll take a look at how CheckboxListTile widget works.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

Leave a Reply