How to implement the CheckboxListTile in Flutter

How to implement the CheckboxListTile in Flutter

In this article, we will discuss how to implement a CheckboxListTile in a flutter. What shall we do today is to select fruit from multiple options. At first, we should know what is CheckboxListTile in flutter is.

CheckboxListTile is a built-in widget in flutter which is a combination of CheckBox with a ListTile. A checkbox is a type of input component which holds the Boolean value. It is a GUI element that allows the user to choose multiple options from several selections. Here, a user can answer only in yes or no value. A marked/checked checkbox means yes, and an unmarked/unchecked checkbox means no value. Typically, we can see the checkboxes on the screen as a square box with white space or a tick mark. A label or caption corresponding to each checkbox described the meaning of the checkboxes.

Properties of CheckboxListTile are given below

autofocus takes in a boolean as the value to divide whether the widget will be selected on the initial focus or not.
activeColorspecified the color of the selected checkbox.
checkColorassigns a color to the check icon by taking in the Color class as the object.
contentPaddingto assign empty space inside the widget by taking in EdgeIsetsGeometry class as the object.
controlAffinityholds the ListTileControlAffinity class as the object to decide the location of action in respect to text inside the widget.
densetakes in a boolean as the object whether is associated with the vertical dense list.
isThreeLinetakes in a boolean as the object to decide whether the text in the widget will be printed till the third line.
onChangedIt will be called when the value is changed.
secondarythe property holds a widget as the object to be displayed on the opposite side of the checkbox.
selectedBy default, it is false. It highlights the text after selection.
subtitle Usually to add the description.
valueIt is used whether the checkbox is checked or not.

Let’s take an example of how we can implement the DropDownButton in our flutter application.

we will create a new model name Fruits that includes the String of text and Boolean value for displaying the fruit or not and store it in a new file inside the lib folder name fruit.dart

class Fruit {
  String text;
  bool value;

  Fruit({
    required this.text,
    this.value = false,
  });
}
import 'package:flutter/material.dart';
import 'package:vlogpost/model/fruit.dart';

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

  @override
  State<CheckBoxScreen> createState() => _CheckBoxScreenState();
}

class _CheckBoxScreenState extends State<CheckBoxScreen> {
  final selectAllFruits = Fruit(text: 'Select All Fruits');
  final fruits = [
    Fruit(text: 'Apple'),
    Fruit(text: 'Grape'),
    Fruit(text: 'Orange'),
    Fruit(text: 'Mango'),
    Fruit(text: 'Banana'),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('CheckBox in Flutter'),
          centerTitle: true,
        ),
        body: ListView(children: [
          CheckboxListTile(
              activeColor: Colors.green,
              title: Text(
                selectAllFruits.text,
                style: const TextStyle(fontSize: 16),
              ),
              controlAffinity: ListTileControlAffinity.leading,
              value: selectAllFruits.value,
              onChanged: (value) {
                if (value == null) return;
                setState(() {
                  selectAllFruits.value = value;
                  fruits.forEach((element) => element.value = value);
                });
              }),
          const Padding(
            padding: EdgeInsets.all(8.0),
            child: Divider(
              height: 1,
              thickness: 2,
            ),
          ),
          ...fruits.map((customCheckListTile)).toList()
        ]));
  }

  Widget customCheckListTile(Fruit fruit) {
    return CheckboxListTile(
        activeColor: Colors.green,
        title: Text(
          fruit.text,
          style: const TextStyle(fontSize: 16),
        ),
        controlAffinity: ListTileControlAffinity.leading,
        value: fruit.value,
        onChanged: (value) {
          setState(() {
            fruit.value = value!;
            selectAllFruits.value = fruits.every((element) => element.value);
          });
        });
  }
}

In the above code, we have used a list of fruit and displayed it in UI by using the map method. Similarly, we have used the forEach method to select all the fruit when the user toggles on the select all fruits. it will select all the fruit from it. When the user selects all fruit from the list at some specific time then at that time the user unselects one of the checkbox items then it will directly reflect to unchange the select all fruits. for this, we have used every method that checks the value of the element and stores the variable in selectAllFruits.

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thanks for reading this article on implementing CheckboxListTile in Flutter.

Also Read: How To Implement DropDownButton in Flutter.