How to use Flutter Checkbox widget

A checkbox is a Material Design widget that allows users to select one or more options from a list. It is a simple but effective way for users to interact with your app and provide feedback by tapping a small square box.

Constructor and parameters

The Radio widget provides a constructor with various parameters to customize its behavior and layout.

Checkbox({
  Key? key,
  required bool? value, 
  bool tristate = false, 
  required ValueChanged<bool?>? onChanged, 
  MouseCursor? mouseCursor, 
  Color? activeColor, 
  MaterialStateProperty<Color?>? fillColor, 
  Color? checkColor,
  Color? focusColor,
  Color? hoverColor, 
  MaterialStateProperty<Color?>? overlayColor, 
  double? splashRadius, 
  MaterialTapTargetSize? materialTapTargetSize, 
  VisualDensity? visualDensity, 
  FocusNode? focusNode, 
  bool autofocus = false,
  OutlinedBorder? shape, 
  BorderSide? side, 
  bool isError = false
})

Let's take a closer look at each parameter and its purpose:

  • key: An optional key that uniquely identifies the Checkbox widget.

  • value: It is a required boolean value that determines whether the checkbox is currently selected (true) or deselected (false).

  • tristate: A optional boolean value for checking whether the checkbox can have a third state in addition to being selected or deselected. By default, it is set to false.

  • onChanged: A required callback function that is called when the checkbox is tapped. It takes a boolean parameter representing the new state of the checkbox.

  • mouseCursor: An optional parameter that tells the mouse cursor to be used when hovering over the checkbox.

  • activeColor: An optional parameter that defines the checkbox's color when selected.

  • fillColor: An optional material state property that defines the color of the checkbox's fill when selected.

  • checkColor: An optional color that defines the color of the checkmark inside the checkbox.

  • focusColor: An optional color that defines the color of the checkbox when it is focused.

  • hoverColor: An optional color that defines the color of the checkbox when it is being hovered over.

  • overlayColor: An optional material state property that defines the color of the overlay that appears on top of the checkbox when pressed.

  • splashRadius: An optional radius value that defines the size of the splash effect when the checkbox is pressed.

  • materialTapTargetSize: An optional material tap target size that defines the minimum size of the tap target area for the checkbox.

  • visualDensity: An optional visual density that adjusts the spacing and layout of the checkbox.

  • focusNode: An optional focus node that can be used to control the focus state of the checkbox manually.

  • autofocus: A boolean value indicating whether the checkbox should automatically focus itself when the widget is first inserted into the tree.

  • shape: An optional outlined border that defines the shape of the checkbox.

  • side: An optional border side that defines the border of the checkbox.

  • isError: A boolean value indicating whether the checkbox should be styled as an error.

Implementation

We can follow the instructions given below to add a CheckBox widget in UI:

Import the necessary packages

To use the CheckBox widget, we need to import the flutter/material.dart package into your Dart file.

import 'package:flutter/material.dart';

Declaring variables

We need to declare isChecked variable just above the build, which will hold the current state of CheckBox widgets.

Adding a simple checkbox widget

Below is a sample code of the Flutter CheckBox widget.

ListTile(
title: Text('Educative Answers'),
leading: Checkbox(
value: isChecked,
onChanged: (value) {
setState(() {
isChecked = value;
});
},
),
)

Code explanation

  • Line 1: This line contains a ListTile widget. The ListTile widget represents a single fixed-height row typically containing some text and optional leading and trailing widgets.

  • Line 2: The title property of the ListTile is set to a Text widget with the text 'Educative Answers'. This text will be displayed as the main title of the ListTile.

  • Line 3: The leading property of the ListTile is set to a Checkbox widget.

  • Line 4: value: isChecked assigns the value of the Checkbox to the isChecked boolean variable. This determines whether the checkbox is currently selected or not.

  • Lines 59: The onChanged callback is provided to the Checkbox. This callback is triggered when the checkbox is tapped or its state changes. It takes a parameter value, which represents the new state of the checkbox.

  • Line 6: setState(() { ... }) is used to update the state of the widget. Whenever the checkbox is tapped, and the onChanged callback is called, this method is invoked to rebuild the widget with the updated state.

  • Line 7: Inside the setState method, isChecked = value updates the value of the isChecked variable with the new state of the checkbox.

Output

Simple CheckBox Widget
Simple CheckBox Widget

Tristate Checkbox widget

The Checkbox widget can also have three states: selected, unselected, and intermediate. We can achieve it by just adding a property tristate to the Checkbox widget just like given below:

Checkbox(
value: null,
onChanged: (value) {},
tristate: true,
)

We can also control the value in the onChanged() callback function to set it to true if we want it to be selected, false if we want it to be unselected, and null if we want it to be in an intermediate state, as mentioned in the above section.

Output

CheckBox Widget with tristate properties
CheckBox Widget with tristate properties

Complete code

We get the following output by putting together the code explained above.

import 'package:flutter/material.dart';  
  
void main() {  
  runApp(MaterialApp( home: MyHomePage(),));  
}  
  
class MyHomePage extends StatefulWidget {  
  @override  
  _HomePageState createState() => _HomePageState();  
}  
  
class _HomePageState extends State<MyHomePage> {  
  bool _first = false;  
  bool _second = true;
  bool _third = null;  
  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      home: Scaffold(  
        appBar: AppBar(title: Text('Educative Answers'),),  
        body: Container(  
            child: Column(  
              children: <Widget>[  
                ListTile(
                  title: Text('False CheckBox'),
                  leading: Checkbox(
                    value: _first,
                    onChanged: (value) {
                      setState(() {
                        _first = value;
                      });
                    },
                    
                  ),
                ),
                ListTile(
                  title: Text('True CheckBox'),
                  leading: Checkbox(
                    value: _second,
                    onChanged: (value) {
                      setState(() {
                        _second = value;
                      });
                    },
                  ),
                ),
                ListTile(
                  title: Text('Tristate CheckBox'),
                  leading: Checkbox(
                    value: _third,
                    onChanged: (value) {
                      setState(() {
                        _third = value;
                      });
                    },
                    tristate: true,
                  ),
                ),  
              ],  
            )  
        ),  
      ),  
    );  
  }  
}  

Conclusion

We learned how to use the Checkbox widget in Flutter. We explored creating a Checkbox and customizing its appearance and behavior using properties such as activeColor, tristate, and onChanged. We also learned how to handle the state of a Checkbox in the onChanged callback. Using the Checkbox widget, we can provide users with intuitive options for selection in our Flutter applications.

Review Questions

1

Which property defines the color of the checkbox when it is selected?

A)

activeColor

B)

checkColor

C)

focusColor

Question 1 of 30 attempted
Copyright ©2024 Educative, Inc. All rights reserved