flutter checkboxes with labels column row

How to use Flutter Checkbox widget – guide with examples

Content

  • What is the Flutter Checkbox widget
  • Flutter Checkbox widget properties
  • How to use the Checkbox widget in Flutter
  • Tristate Checkbox widget in Flutter
  • Flutter Checkbox Checked State
  • Flutter Checkbox Unchecked State
  • Flutter Checkbox Indeterminate State
  • Flutter checkbox with the label
  • What is the Flutter CheckboxListTile widget
  • Toggle between multiple checkboxes where only one can be selected
  • How do I make a checkbox not clickable in Flutter
  • How do I set a default value to Flutter checkbox
  • How do you store checkbox value in Flutter
  • How do you save checkbox value in Flutter
  • How to use multiple checkboxes in a row in Flutter
  • Multiple checkboxes with labels in a Row
  • How to evenly align the Flutter multiple Checkboxes in a Row
  • How to get value from multiple checkboxes in Flutter
  • How to set checkbox value dynamically in Flutter
  • How do I check a checkbox dynamically in Flutter
  • How do I click all checkboxes at once in Flutter
  • Select all checkboxes at once in Flutter
  • Select/deselect all checkboxes in Flutter
  • How do I make a list of checkboxes in Flutter
  • How to customize the flutter checkbox widget
  • Changing the checkbox colour
  • Changing the checkbox shape
  • Change the checkbox appearance with a Container and BoxDecoration
  • How do I change the size of a checkbox in Flutter
  • How do I align a checkbox with label in Flutter
  • How to align a CheckboxListTile to the left in Flutter
  • How to make the checkbox required in Flutter
  • How do I verify if Flutter checkbox is checked
  • How to create a custom checkbox in Flutter

What is the Flutter Checkbox widget

The Flutter Checkbox widget is a graphical user interface element that allows users to make a binary selection, typically between two options: checked or unchecked. It consists of a small box and a label, and when the box is clicked or tapped, it toggles between being checked and unchecked. This widget is commonly used in forms, settings screens, and other scenarios where users need to make a yes or no choice.

Visually, the Checkbox widget typically appears as a small square box with or without a checkmark inside it. The label associated with the checkbox provides a textual description of the option it represents. When the checkbox is checked, the box is usually filled with a contrasting colour or displays a checkmark to indicate the selected state. Conversely, when it is unchecked, the box is usually empty.

Flutter Checkbox widget properties

  • Key? key – Controls how one widget replaces another widget in the tree.
  • required bool? value – Whether this checkbox is checked.
  • bool tristate = false – If true the checkbox’s value can be true, false, or null.
  • required void Function(bool?)? onChanged – Called when the value of the checkbox should change.
  • MouseCursor? mouseCursor – The cursor for a mouse pointer when it enters or is hovering over the widget.
  • Color? activeColor – The colour to use when this checkbox is checked.
  • MaterialStateProperty? fillColor – The color that fills the checkbox, in all MaterialStates.
  • Color? checkColor – The colour to use for the check icon when this checkbox is checked.
  • Color? focusColor – The colour for the checkbox’s Material when it has the input focus.
  • Color? hoverColor – The colour for the checkbox’s Material when a pointer is hovering over it.
  • MaterialStateProperty? overlayColor – The colour for the checkbox’s Material.
  • double? splashRadius – The splash radius of the circular Material ink response.
  • MaterialTapTargetSize? materialTapTargetSize – Configures the minimum size of the tap target.
  • VisualDensity? visualDensity – Defines how compact the checkbox’s layout will be.
  • FocusNode? focusNode – An optional focus node to use as the focus node for this widget.
  • bool autofocus = false – True if this widget will be selected as the initial focus when no other node in its scope is currently focused.
  • OutlinedBorder? shape – The shape of the checkbox’s Material.
  • BorderSide? side – The colour and width of the checkbox’s border.
  • bool isError = false – True if this checkbox wants to show an error state.

How to use the Checkbox widget in Flutter

Here’s a simple code example that demonstrates how to use the Checkbox widget in Flutter:

bool _isChecked = false;

Container(
  padding: EdgeInsets.all(10),
  child: Checkbox(
    value: _isChecked,
    onChanged: (value) {
      setState(() {
        _isChecked = value!;
      });
    },
  )
)
flutter checkbox

In this example, we start by declaring a boolean variable _isChecked and setting it to false, which represents the initial state of the checkbox.

Then, we use a Container widget to provide padding around the Checkbox widget. The padding property is set to EdgeInsets.all(10), which adds 10 pixels of padding on all sides.

Inside the Container, we use the Checkbox widget. The value property is set to _isChecked, which determines whether the checkbox is checked or unchecked based on the value of the _isChecked variable.

To handle the state changes of the checkbox, we assign an onChanged callback function to the onChanged property of the Checkbox widget. This function is triggered whenever the checkbox is tapped. Inside the callback function, we update the value of _isChecked based on the new value passed to the onChanged callback. We wrap this update inside setState to notify Flutter that the state has changed, triggering a rebuild of the widget and reflecting the new checkbox state.

Tristate Checkbox widget in Flutter

The Flutter Checkbox widget has three states: checked, unchecked, and indeterminate.

In simple terms, the checked state indicates that the Checkbox is selected, the unchecked state means it is not selected, and the indeterminate state represents a state of uncertainty or partial selection. These states can be controlled by setting the value property of the Checkbox. The onChanged callback allows you to handle state changes.

flutter checkbox three states

Flutter Checkbox Checked State

In this state, the Checkbox is selected or checked. It indicates that a particular option or condition is chosen or enabled. Visually, you will see a filled-in checkbox indicating the selected state.

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

In this example, the Checkbox is in the checked state. The value property is set to true, indicating that the checkbox is checked. The onChanged callback is an empty function, as the checkbox is not interactive in this case.

Flutter Checkbox Unchecked State

In this state, the Checkbox is not selected or unchecked. It represents that a particular option or condition is not chosen or disabled. Visually, you will see an empty checkbox indicating the unselected state.

Checkbox(
  value: false,
  onChanged: (value) {},
)

In this example, the Checkbox is in the unchecked state. The value property is set to false, indicating that the checkbox is unchecked. Similar to the previous example, the onChanged callback is an empty function.

Flutter Checkbox Indeterminate State

This state represents a state of uncertainty or partial selection. It is typically used when dealing with a group of checkboxes where some options are selected, and others are not. Visually, you will see a checkbox with a horizontal line inside, indicating an indeterminate or partially selected state.

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

In this example, the Checkbox is in the indeterminate state. The value property is set to null, representing an indeterminate state. The onChanged callback is an empty function, and the tristate property is set to true to enable the indeterminate state.

Flutter checkbox with the label

Here’s an example of how to use the Checkbox widget with a label in Flutter with a ListTile

bool _isChecked = false;

ListTile(
  title: Text('Checkbox Example'),
  leading: Checkbox(
    value: _isChecked,
    onChanged: (value) {
      setState(() {
        _isChecked = value!;
      });
    },
  ),
)
flutter checkbox label listtile

In this example, we start by declaring a boolean variable _isChecked and setting it to false, which represents the initial state of the checkbox.

We use the ListTile widget, which is a convenient way to display a row of information. The title property is set to a Text widget with the label “Checkbox Example”.

Inside the ListTile, we use the Checkbox widget as the leading property. The value property is set to _isChecked, which determines whether the checkbox is checked or unchecked based on the value of the _isChecked variable.

The process of handling the checkbox state changes in this example is the same as in the previous example.

What is the Flutter CheckboxListTile widget

Here’s an example of how to use the CheckboxListTile widget in Flutter:

bool _isChecked = false;

CheckboxListTile(
  title: Text('Checkbox Example'),
  value: _isChecked,
  onChanged: (value) {
    setState(() {
      _isChecked = value!;
    });
  },
)
flutter checkbox listtile

In this example, we start by declaring a boolean variable _isChecked and setting it to false, representing the initial state of the checkbox.

We use the CheckboxListTile widget, which combines the functionality of a Checkbox and a ListTile. The title property is set to a Text widget with the label “Checkbox Example”. This label represents the primary content of the list item.

The value property determines whether the checkbox is checked or unchecked based on the value of the _isChecked variable.

The process of handling the checkbox state changes in this example is the same as in the previous example.

Toggle between multiple checkboxes where only one can be selected

To toggle between multiple checkboxes where only one can be selected at a time, you can manage the state of the checkboxes and update their values accordingly. Here’s an example:

int _selectedValue = 0; // Initial selected value

Column(
  children: [
    CheckboxListTile(
      title: Text('Option 1'),
      value: _selectedValue == 1,
      onChanged: (value) {
        setState(() {
          if (value!) {
            _selectedValue = 1;
          }
        });
      },
    ),
    CheckboxListTile(
      title: Text('Option 2'),
      value: _selectedValue == 2,
      onChanged: (value) {
        setState(() {
          if (value!) {
            _selectedValue = 2;
          }
        });
      },
    ),
    CheckboxListTile(
      title: Text('Option 3'),
      value: _selectedValue == 3,
      onChanged: (value) {
        setState(() {
          if (value!) {
            _selectedValue = 3;
          }
        });
      },
    ),
  ],
)
flutter checkbox toggle one selected

In this example, we declare an integer variable _selectedValue to store the value of the selected option. We initialize it to 0, indicating no option is selected initially.

Inside a Column widget, we create multiple CheckboxListTile widgets, each representing an option.

For each CheckboxListTile, we set the value property to _selectedValue == <value>, where <value> is the corresponding value of the option. This expression evaluates to true when the current option is selected and false otherwise.

To handle the state changes and toggle the selection, we assign an onChanged callback function to each CheckboxListTile. When a checkbox is tapped, this function is triggered, and it receives the new value of the checkbox as an argument.

Inside the callback function, we update the value of _selectedValue based on the new value received. We only update _selectedValue when the checkbox is checked (value == true), ensuring that only one option can be selected at a time.

By using setState, we notify Flutter of the state change, triggering a rebuild of the widget and reflecting the updated selection in the UI.

How do I make a checkbox not clickable in Flutter

To make a Checkbox not clickable in Flutter, you can disable its interactive behaviour by setting the onChanged callback to null. Here’s an example:

Checkbox(
  value: true,
  onChanged: null,
)

In this example, the Checkbox is rendered with value set to true, indicating it is checked. However, the onChanged property is set to null, which disables the interactive behaviour of the Checkbox.

By setting onChanged to null, the Checkbox becomes unclickable, and the user cannot change its state by tapping on it. It appears visually as a disabled Checkbox, indicating that its state is fixed and cannot be modified.

You can apply the same approach to any Checkbox widget by setting the onChanged property to null to make it unclickable.

Note that when the onChanged property is set to null, the Checkbox is considered disabled and will not respond to user interactions.

Here is an example of the Checkbox widgets with different states:

Row(
children: [
Checkbox(
value: true,
onChanged: null,
),
Checkbox(
value: false,
onChanged: null,
),
Checkbox(
value: null,
onChanged: null,
tristate: true,
)
],
)
flutter checkbox three states disabled

All three Checkbox widgets have their onChanged properties set to null, indicating that they are not clickable.

The first Checkbox has value: true, so it appears checked but cannot be toggled.

The second Checkbox has value: false, so it appears unchecked and cannot be toggled.

The third Checkbox has value: null and tristate: true, indicating a tristate Checkbox. It appears with an indeterminate state and cannot be toggled.

How do I set a default value to Flutter checkbox

To set a default value to a Flutter Checkbox, you can initialize the corresponding boolean variable to the desired default value. Here’s an example:

bool _isChecked = true; // Default value

Checkbox(
  value: _isChecked,
  onChanged: (value) {
    setState(() {
      _isChecked = value!;
    });
  },
)

In this example, the _isChecked boolean variable is set to true as the default value. This means that the Checkbox will initially appear checked.

By assigning the _isChecked value to the value property of the Checkbox, you ensure that the Checkbox reflects the default value. When _isChecked is true, the Checkbox will be checked, and when it’s false, the Checkbox will be unchecked.

How do you store checkbox value in Flutter

How do you save checkbox value in Flutter

The simplest way to save or store the value of a Flutter Checkbox is by using the SharedPreferences package, which allows you to store key-value.

First, you must add the shared_preferences package to your pubspec.yaml file and then import the package in your Dart file:

dependencies:
  shared_preferences: ^2.0.12
import 'package:shared_preferences/shared_preferences.dart';

Here’s an example of how you can use SharedPreferences to save the Checkbox value (full working code example):

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

bool _checkboxValue = false;

@override
void initState() {
super.initState();
_loadCheckboxValue();
}

void _loadCheckboxValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool? checkboxValue = prefs.getBool('checkboxValue');
setState(() {
_checkboxValue = checkboxValue ?? false;
});
}

void _saveCheckboxValue(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('checkboxValue', value);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
padding: EdgeInsets.all(10),
child: CheckboxListTile(
title: Text('Save Checkbox Value'),
value: _checkboxValue,
onChanged: (value) {
setState(() {
_checkboxValue = value!;
_saveCheckboxValue(value);
});
},
)
)
);
}
}

In this code, a StatefulWidget called CheckboxExample is created. The _checkboxValue boolean variable represents the state of the Checkbox.

The _loadCheckboxValue function is called in the initState method to retrieve the saved Checkbox value from SharedPreferences and update the _checkboxValue variable accordingly.

The _saveCheckboxValue function is used to save the Checkbox value to SharedPreferences whenever it changes.

In the build method, a CheckboxListTile widget is used to display the Checkbox with a title. The value property is set to _checkboxValue, and the onChanged callback updates the _checkboxValue and calls _saveCheckboxValue to persist the value in SharedPreferences.

How to use multiple checkboxes in a row in Flutter

To use multiple Checkboxes in a Row in Flutter, you can follow this code example:

bool _checkboxValue1 = false;
bool _checkboxValue2 = false;
bool _checkboxValue3 = false;

Row(
  children: [
    Checkbox(
      value: _checkboxValue1,
      onChanged: (value) {
        setState(() {
          _checkboxValue1 = value!;
        });
      },
    ),
    Checkbox(
      value: _checkboxValue2,
      onChanged: (value) {
        setState(() {
          _checkboxValue2 = value!;
        });
      },
    ),
    Checkbox(
      value: _checkboxValue3,
      onChanged: (value) {
        setState(() {
          _checkboxValue3 = value!;
        });
      },
    ),
  ],
)
flutter checkboxes row

In this code snippet, we have a Row widget that contains multiple Checkbox widgets. Each Checkbox is defined as a separate child of the Row.

Each checkbox has its own associated boolean variable (_checkboxValue1, _checkboxValue2, _checkboxValue3) to control its state, and an onChanged callback function assigned to handle the state changes. When the user interacts with a checkbox, the corresponding onChanged callback function is triggered. Inside the callback, the associated variable is updated with the new value and setState is called to notify Flutter of the state change and trigger a rebuild of the widget.

Multiple checkboxes with labels in a Row

Here is an example of two checkboxes with labels in a row:

bool checkbox1Value = false;
bool checkbox2Value = false;

Row(
  children: [
    Checkbox(
      value: checkbox1Value,
      onChanged: (value) {
        setState(() {
          checkbox1Value = value!;
        });
      },
    ),
    Text('Checkbox 1'),
    Checkbox(
      value: checkbox2Value,
      onChanged: (value) {
        setState(() {
          checkbox2Value = value!;
        });
      },
    ),
    Text('Checkbox 2'),
    // Add more Checkbox widgets as needed
  ],
)

When the checkboxes exceed the available width you can wrap the Row widget with a SingleChildScrollView widget to enable horizontal scrolling, here is an example:

bool checkbox1Value = false;
bool checkbox2Value = false;
bool checkbox3Value = false;
bool checkbox4Value = false;

SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: Row(
    children: [
      Checkbox(
        value: checkbox1Value,
        onChanged: (value) {
          setState(() {
            checkbox1Value = value!;
          });
        },
      ),
      Text('Checkbox 1'),
      Checkbox(
        value: checkbox2Value,
        onChanged: (value) {
          setState(() {
            checkbox2Value = value!;
          });
        },
      ),
      Text('Checkbox 2'),
      Checkbox(
        value: checkbox3Value,
        onChanged: (value) {
          setState(() {
            checkbox3Value = value!;
          });
        },
      ),
      Text('Checkbox 2'),
      Checkbox(
        value: checkbox4Value,
        onChanged: (value) {
          setState(() {
            checkbox4Value = value!;
          });
        },
      ),
      Text('Checkbox 2'),
      // Add more Checkbox widgets as needed
    ],
  ),
)
flutter checkboxes row singlechildscrollview

In this code snippet, we wrap the Row widget with a SingleChildScrollView widget to enable horizontal scrolling when the checkboxes exceed the available width.

Each checkbox is defined with its own value property, representing the state of the checkbox, and an onChanged callback to handle state changes. The associated labels are displayed using Text widgets.

How to evenly align the Flutter multiple Checkboxes in a Row

To evenly align multiple checkboxes with labels in a row in Flutter, you can use the Expanded widget along with the Column widget. Here’s an example that includes boolean variables for each checkbox:

bool checkbox1Value = false;
bool checkbox2Value = false;
bool checkbox3Value = false;
bool checkbox4Value = false;

Row(
  children: [
    Expanded(
      child: Column(
        children: [
          Checkbox(
            value: checkbox1Value,
            onChanged: (value) {
              setState(() {
                checkbox1Value = value!;
              });
            },
          ),
          Text('Checkbox 1'),
        ],
      ),
    ),
    Expanded(
      child: Column(
        children: [
          Checkbox(
            value: checkbox2Value,
            onChanged: (value) {
              setState(() {
                checkbox2Value = value!;
              });
            },
          ),
          Text('Checkbox 2'),
        ],
      ),
    ),
    Expanded(
      child: Column(
        children: [
          Checkbox(
            value: checkbox3Value,
            onChanged: (value) {
              setState(() {
                checkbox3Value = value!;
              });
            },
          ),
          Text('Checkbox 3'),
        ],
      ),
    ),
    Expanded(
      child: Column(
        children: [
          Checkbox(
            value: checkbox4Value,
            onChanged: (value) {
              setState(() {
                checkbox4Value = value!;
              });
            },
          ),
          Text('Checkbox 4'),
        ],
      ),
    ),
  ],
)
flutter checkboxes with labels column row

In this code example, each checkbox is wrapped inside an Expanded widget, which ensures equal distribution of available space within the Row. The checkboxes are contained within a Column widget, allowing for vertical alignment of the checkbox and its associated label.

The boolean variables checkbox1Value, checkbox2Value, checkbox3Value, and checkbox4Value represent the state of each checkbox. When a checkbox is tapped, the corresponding onChanged callback is triggered, updating the associated variable and triggering a rebuild using setState.

By using the Expanded widget along with the Column widget, the checkboxes and labels will be evenly aligned and occupy equal space horizontally.

How to get value from multiple checkboxes in Flutter

To get the values from multiple checkboxes in Flutter, you can create a list of boolean variables to represent the state of each checkbox. Here’s an example of how you can achieve this:

  1. Define a list of boolean variables to track the state of each checkbox:
List<bool> checkboxValues = [false, false, false];
  1. Create the checkboxes using a ListView.builder widget:
ListView.builder(
  itemCount: checkboxValues.length,
  itemBuilder: (BuildContext context, int index) {
    return CheckboxListTile(
      value: checkboxValues[index],
      onChanged: (value) {
        setState(() {
          checkboxValues[index] = value!;
        });
      },
      title: Text('Checkbox ${index + 1}'),
    );
  },
)
  1. To retrieve the values of the checkboxes, you can use the checkboxValues list:
void getValueFromCheckboxes() {
  for (int i = 0; i < checkboxValues.length; i++) {
    bool value = checkboxValues[i];
    print('Checkbox ${i + 1} value: $value');
  }
}

In this example, we use a ListView.builder to dynamically create checkboxes based on the length of the checkboxValues list. Each checkbox is represented by a CheckboxListTile widget, which allows for a title or label to be associated with the checkbox.

When a checkbox’s state changes, the corresponding onChanged callback is triggered, updating the value in the checkboxValues list.

To access the values of the checkboxes, you can iterate through the checkboxValues list and retrieve the boolean value for each checkbox.

Here is a code example with an extra ElevatedButton which will print values in the console:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

List<bool> checkboxValues = [false, false, false];

void getValueFromCheckboxes() {
for (int i = 0; i < checkboxValues.length; i++) {
bool value = checkboxValues[i];
print('Checkbox ${i + 1} value: $value');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Column(
children: [
ElevatedButton(
onPressed: () {
setState(() {
getValueFromCheckboxes();
});
},
child: Text('Get Checkbox Values'),
),

Text("Values are printed in the console"),
Expanded(
child: ListView.builder(
itemCount: checkboxValues.length,
itemBuilder: (BuildContext context, int index) {
return CheckboxListTile(
value: checkboxValues[index],
onChanged: (value) {
setState(() {
checkboxValues[index] = value!;
});
},
title: Text('Checkbox ${index + 1}'),
);
},
),
),
],
)
);
}
}

When the ElevatedButton is pressed, the getValueFromCheckboxes function is called, printing the checkbox values to the console.

To display the values in a Text widget, you can make a few modifications to the above code:

List<bool> checkboxValues = [false, false, false];
String displayedValues = '';

void getValueFromCheckboxes() {
  displayedValues = '';
  for (int i = 0; i < checkboxValues.length; i++) {
    bool value = checkboxValues[i];
    displayedValues += 'Checkbox ${i + 1} value: $value\n';
  }
}

Column(
        children: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                getValueFromCheckboxes();
              });
            },
            child: Text('Get Checkbox Values'),
          ),
          Text("Values:"),
          Text(displayedValues),
          Expanded(
            child: ListView.builder(
              itemCount: checkboxValues.length,
              itemBuilder: (BuildContext context, int index) {
                return CheckboxListTile(
                  value: checkboxValues[index],
                  onChanged: (value) {
                    setState(() {
                      checkboxValues[index] = value!;
                    });
                  },
                  title: Text('Checkbox ${index + 1}'),
                );
              },
            ),
          ),
        ],
      )
flutter checkboxes get values

In this modified code, we added a new variable displayedValues to store the values of the checkboxes. The getValueFromCheckboxes function now assigns the checkbox values to the displayedValues string instead of printing them to the console. The displayedValues string is then displayed in a Text widget below the ElevatedButton.

How to set checkbox value dynamically in Flutter

How do I check a checkbox dynamically in Flutter

To check a checkbox dynamically in Flutter, you can update the value of the boolean variable that controls the checkbox’s state. Here’s an example:

bool checkboxValue = false;

// To check the checkbox dynamically
setState(() {
  checkboxValue = true;
});

In this code snippet, checkboxValue is a boolean variable that represents the state of the checkbox. Initially, it is set to false, indicating an unchecked state.

To check the checkbox dynamically, you can call setState and update the value of checkboxValue to true. This change will trigger a rebuild of the widget, and the checkbox will be displayed as checked.

bool checkboxValue = false;

Checkbox(
  value: checkboxValue,
  onChanged: (newValue) {
    setState(() {
      checkboxValue = newValue!;
    });
  },
);

How do I click all checkboxes at once in Flutter

Select all checkboxes at once in Flutter

To select all checkboxes at once, you need to maintain a list of boolean variables that represent the state of each checkbox. By updating all the boolean values in the list to true, you can simulate selecting all checkboxes simultaneously. Here’s an example:

List<bool> checkboxValues = [false, false, false]; // List of checkbox states

// To select all checkboxes at once
setState(() {
  checkboxValues = List.filled(checkboxValues.length, true);
});

In this code snippet, checkboxValues is a list of boolean variables that represent the state of each checkbox. Initially, all the checkboxes are set to false, indicating an unchecked state.

To select all checkboxes at once, you can call setState and update checkboxValues using List.filled to create a new list with all values set to true. This will update the state of all checkboxes, and the UI will reflect the selected state for all checkboxes.

Here’s an example code that demonstrates how to create a list of checkboxes with labels and an ElevatedButton to select all checkboxes at once:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

List<bool> checkboxValues = [false, false, false]; // List of checkbox states

void selectAllCheckboxes() {
setState(() {
checkboxValues = List.filled(checkboxValues.length, true);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Column(
children: [
ElevatedButton(
onPressed: selectAllCheckboxes,
child: Text('Select All Checkboxes'),
),
ListView.builder(
shrinkWrap: true,
itemCount: checkboxValues.length,
itemBuilder: (BuildContext context, int index) {
return CheckboxListTile(
value: checkboxValues[index],
onChanged: (value) {
setState(() {
checkboxValues[index] = value!;
});
},
title: Text('Checkbox ${index + 1}'),
);
},
),
],
)
);
}
}
flutter select all checkboxes

In this example the selectAllCheckboxes function is called when the ElevatedButton is pressed, and it updates all the boolean values in checkboxValues to true, thus selecting all checkboxes at once.

The checkboxes are rendered using a ListView.builder, and the onChanged callback is used to update the state of individual checkboxes when they are tapped.

Select/deselect all checkboxes in Flutter

To select or deselect all checkboxes at once in Flutter, you can use a single boolean variable to represent the state of all checkboxes. When the “Select All” button is pressed, you can update this variable and trigger a rebuild of the checkboxes to reflect the updated state. Here’s an example:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

List<bool> checkboxValues = [false, false, false]; // List of checkbox states
bool selectAll = false; // State variable for selecting/deselecting all checkboxes

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Column(
children: [
// Select All button
ElevatedButton(
onPressed: () {
setState(() {
selectAll = !selectAll;
checkboxValues = List.filled(checkboxValues.length, selectAll);
// Perform any other desired actions
});
},
child: Text(selectAll ? 'Deselect All' : 'Select All'),
),
Expanded(
child: ListView.builder(
itemCount: checkboxValues.length,
itemBuilder: (BuildContext context, int index) {
return CheckboxListTile(
value: checkboxValues[index],
onChanged: (value) {
setState(() {
checkboxValues[index] = value!;
// Perform any other desired actions
});
},
title: Text('Checkbox ${index + 1}'),
);
},
),
),
],
)
);
}
}
flutter deselect all checkboxes

In this code snippet, we have a list of boolean variables (checkboxValues) that represent the state of each checkbox. We also have a boolean variable (selectAll) to track whether all checkboxes should be selected or deselected.

When the “Select All” button is pressed, the onPressed callback updates the selectAll variable to its opposite value (toggling between select all and deselect all). Then, the checkboxValues list is updated using List.filled() to set all checkbox values to the value of selectAll.

By using the setState function, we trigger a rebuild of the widget tree, causing the checkboxes to reflect the updated state. The button’s label is also updated based on the selectAll variable, displaying either “Select All” or “Deselect All” text.

How do I make a list of checkboxes in Flutter

To create a list of checkboxes in Flutter, you can use the ListView.builder widget along with a CheckboxListTile for each item in the list. Here’s an example:

List<bool> checkboxValues = [false, false, false, true, true]; // List of checkbox states

ListView.builder(
  itemCount: checkboxValues.length,
  itemBuilder: (BuildContext context, int index) {
    return CheckboxListTile(
      value: checkboxValues[index],
      onChanged: (value) {
        setState(() {
          checkboxValues[index] = value!;
          // Perform any other desired actions
        });
      },
      title: Text('Checkbox ${index + 1}'),
    );
  },
)
flutter checkboxes listview

In this code snippet, we define a list of boolean variables (checkboxValues) to represent the state of each checkbox. The ListView.builder widget builds a list of CheckboxListTile widgets based on the length of checkboxValues.

Inside the CheckboxListTile, we assign the corresponding value from checkboxValues to the value property of the checkbox. The onChanged callback is responsible for updating the state when the checkbox is toggled. It uses setState to trigger a rebuild of the widget and updates the respective value in checkboxValues based on the new value passed to the onChanged callback.

You can customize the appearance and behaviour of the CheckboxListTile widget further by modifying its properties, such as title, subtitle, secondary, etc., based on your specific requirements.

How to customize the flutter checkbox widget

To customize the Flutter Checkbox widget, you can modify its properties or wrap it with other widgets to achieve the desired appearance and behaviour. Here are a few customization options:

Changing the checkbox colour

To change the colours of the Flutter Checkbox widget, you can customize its appearance using the following properties:

  1. activeColor: Sets the colour of the checkbox when it is checked.
  2. checkColor: Sets the colour of the check icon inside the checkbox when it is checked.
  3. fillColor: Sets the colour of the checkbox’s background when it is checked.
  4. hoverColor: Sets the colour of the checkbox when it is being hovered over.
  5. overlayColor: Sets the colour of the checkbox when it is being pressed.
  6. splashRadius: Sets the size of the splash effect when the checkbox is being pressed.

Here’s an example that demonstrates how to change the colours of the Checkbox widget:

bool isChecked = true;

Checkbox(
  value: isChecked,
  onChanged: (value) {
    setState(() {
      isChecked = value!;
    });
  },
  activeColor: Colors.green, // Change the color when the checkbox is checked
  checkColor: Colors.black, // Change the color of the check icon when the checkbox is checked
  fillColor: MaterialStateProperty.all(Colors.green), // Change the color of the checkbox's background when it is checked
  hoverColor: Colors.yellow, // Change the color when the checkbox is being hovered over
  overlayColor: MaterialStateProperty.all(Colors.red), // Change the color when the checkbox is being pressed
  splashRadius: 20, // Change the size of the splash effect when the checkbox is being pressed
)

Changing the checkbox shape

To change the shape of the Flutter Checkbox widget using the shape property, you can specify different shapes available in the BorderRadius class. Here are examples of different shapes you can use:

  1. Circle:
bool isChecked = true;

Checkbox(
  value: isChecked,
  onChanged: (value) {
    setState(() {
      isChecked = value!;
    });
  },
  shape: CircleBorder(),
)
  1. Rounded Rectangle:
bool isChecked = true;

Checkbox(
  value: isChecked,
  onChanged: (value) {
    setState(() {
      isChecked = value!;
    });
  },
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(8),
  ),
)
  1. Beveled Rectangle:
bool isChecked = true;

Checkbox(
  value: isChecked,
  onChanged: (value) {
    setState(() {
      isChecked = value!;
    });
  },
  shape: BeveledRectangleBorder(
    borderRadius: BorderRadius.circular(8),
  ),
)

Change the checkbox appearance with a Container and BoxDecoration

To change the appearance of the Flutter Checkbox widget using a Container and BoxDecoration, you can wrap the Checkbox widget with a Container and provide a BoxDecoration to customize the checkbox’s visual style. Here’s an example:

bool isChecked = true;

Container(
  decoration: BoxDecoration(
    shape: BoxShape.circle,
    color: Colors.blue,
    border: Border.all(
      color: Colors.black,
      width: 2.0,
    ),
  ),
  child: Checkbox(
    value: isChecked,
    onChanged: (value) {
      setState(() {
        isChecked = value!;
      });
    },
  ),
)

In this example, the Checkbox widget is wrapped with a Container. The Container is styled using a BoxDecoration, which provides the desired visual properties for the checkbox. In this case, the BoxDecoration sets a circular shape with a blue colour and a black border with a width of 2.0.

You can further customize the appearance of the checkbox by adjusting the properties of the BoxDecoration, such as the shape, colour, border, and more, according to your design requirements.

How do I change the size of a checkbox in Flutter

To change the size of a Flutter Checkbox widget, you can wrap it in a Transform.scale widget. Here’s how you can achieve it:

bool isChecked = true;

Transform.scale(
  scale: 1.5, // Adjust the scale factor to increase/decrease size
  child: Checkbox(
    value: isChecked,
    onChanged: (value) {
      setState(() {
        isChecked = value!;
      });
    },
  ),
)

By wrapping the Checkbox widget with Transform.scale and adjusting the scale factor, you can increase or decrease the size of the checkbox. A scale factor greater than 1 will make the checkbox larger, while a scale factor less than 1 will make it smaller.

How do I align a checkbox with label in Flutter

The alignment of the checkbox with its label can be achieved by adjusting the order of the Checkbox and Text widgets within each Row. Here’s the modified code with the description:

  bool isChecked1 = true;
  bool isChecked2 = true;

  Container(
  padding: EdgeInsets.symmetric(horizontal: 10),
  child: Column(
    children: [
      Row(
        children: [
          Checkbox(
            value: isChecked1,
            onChanged: (value) {
              setState(() {
                isChecked1 = value!;
              });
            },
          ),
          Text('Checkbox Label'),
        ],
      ),
      Row(
        children: [
          Text('Checkbox Label'),
          Checkbox(
            value: isChecked2,
            onChanged: (value) {
              setState(() {
                isChecked2 = value!;
              });
            },
          ),
        ],
      ),
    ],
  ),
)
flutter checkbox alignment

In the first Row, the Checkbox widget appears before the Text widget, resulting in the checkbox being aligned to the left and the label being aligned to the right.

In the second Row, the Text widget appears before the Checkbox widget, causing the label to be aligned to the left and the checkbox to be aligned to the right.

To align all the children of the second row to the right, you can wrap them in an Expanded widget. Here’s the modified code:

  bool isChecked1 = true;
  bool isChecked2 = true;

  Container(
  padding: EdgeInsets.symmetric(horizontal: 10),
  child: Column(
    children: [
      Row(
        children: [
          Checkbox(
            value: isChecked1,
            onChanged: (value) {
              setState(() {
                isChecked1 = value!;
              });
            },
          ),
          Text('Checkbox Label'),
        ],
      ),
      Row(
        children: [
          Expanded(
            flex: 1,
            child: Align(
              alignment: Alignment.centerRight,
              child: Text('Checkbox Label'),
            ),
          ),
          Checkbox(
            value: isChecked2,
            onChanged: (value) {
              setState(() {
                isChecked2 = value!;
              });
            },
          ),
        ],
      ),
    ],
  ),
)
flutter checkbox right alignment

In the second Row, the Expanded widget wraps the Text widget and occupies the remaining space in the row. The Expanded widget expands to fill the available space and pushes the Checkbox widget to the right.

In the second Row, the Expanded widget wraps the Text widget and occupies the remaining space in the row. By setting its flex property to 1, it expands to fill the available space and pushes the Checkbox widget to the right.

The Align widget is used to align the Text widget to the right within the expanded space. By setting its alignment property to Alignment.centerRight, the Text widget is aligned to the right side of the expanded area.

How to align a CheckboxListTile to the left in Flutter

To align a CheckboxListTile to the left in Flutter, you can use the ListTileControlAffinity set to ListTileControlAffinity.leading. Here’s an example using the attached code:

  bool isChecked1 = true;
  bool isChecked2 = true;

  Column(
  children: [
    CheckboxListTile( //checkbox positioned at right
      value: isChecked1,
      onChanged: (bool? value) {
        setState(() {
          isChecked1 = value!;
        });
      },
      title: Text("Do you really want to build Mobile App?"),
    ),
    CheckboxListTile( //checkbox positioned at left
      value: isChecked2,
      controlAffinity: ListTileControlAffinity.leading,
      onChanged: (bool? value) {
        setState(() {
          isChecked2 = value!;
        });
      },
      title: Text("Do you really want to learn Flutter?"),
    ),
  ],
),
flutter checkboxlisttile alignment

By setting the controlAffinity property to ListTileControlAffinity.leading, the checkbox will be positioned to the left of the tile.

How to make the checkbox required in Flutter

How do I verify if Flutter checkbox is checked

In Flutter, there is no built-in property to mark a checkbox as required. However, you can implement a custom validation mechanism to ensure that a checkbox is checked before proceeding with form submission or any other action.

Here’s an example of how you can make a checkbox required in Flutter:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

bool isChecked = false;
bool isCheckboxError = false;

// Function to handle checkbox validation
void validateCheckbox() {
setState(() {
// Check if the checkbox is checked
if (isChecked) {
isCheckboxError = false;
// Checkbox is checked, perform desired actions
} else {
isCheckboxError = true;
// Checkbox is not checked, show error message or perform desired actions
}
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Column(
children: [
Checkbox(
value: isChecked,
onChanged: (value) {
setState(() {
isChecked = value!;
});
},
),
Text('I agree to the terms and conditions'),
if (isCheckboxError)
Text(
'Please check the checkbox',
style: TextStyle(
color: Colors.red,
),
),
ElevatedButton(
onPressed: validateCheckbox,
child: Text('Submit'),
),
],
),
)
);
}
}
flutter verify checkbox

In this example, the validateCheckbox function is called when the submit button is pressed. It checks if the checkbox is checked (isChecked is true) and sets the isCheckboxError flag accordingly. You can display an error message or perform any desired actions based on the value of isCheckboxError.

Note that this is a basic example, and you can modify it according to your specific requirements and validation logic.

How to create a custom checkbox in Flutter

To create a custom checkbox in Flutter, you can use a combination of a GestureDetector, a Container, and custom styling. Here’s an example of how you can create a custom checkbox:

bool isChecked = false;

GestureDetector(
  onTap: () {
    setState(() {
      isChecked = !isChecked;
    });
  },
  child: Container(
    width: 44,
    height: 44,
    decoration: BoxDecoration(
      shape: BoxShape.circle,
      border: Border.all(
        color: Colors.grey,
        width: 2.0,
      ),
      color: isChecked ? Colors.blue : Colors.transparent,
    ),
    child: isChecked
        ? Icon(
      Icons.check,
      size: 36,
      color: Colors.white,
    )
        : null,
  ),
),
flutter custom checkbox

In this example, the custom checkbox is wrapped with a GestureDetector widget to detect taps. When the checkbox is tapped, the onTap callback function is triggered, toggling the isChecked variable.

The custom checkbox is represented by a Container widget with a specified width and height. The Container’s decoration property is used to define the shape (circle) and the border style of the checkbox. The colour of the checkbox is determined based on the isChecked variable.

When the checkbox is checked (isChecked is true), an Icon widget with the checkmark icon is displayed inside the Container.

You can further customize the appearance of the checkbox by modifying the properties of the Container, such as the border colour, background colour, size, and the Icon widget.