0
0
FlutterHow-ToBeginner · 3 min read

How to Create Checkbox in Flutter: Simple Guide

In Flutter, you create a checkbox using the Checkbox widget. You control its state with a boolean variable and update it using the onChanged callback to reflect user interaction.
📐

Syntax

The Checkbox widget requires two main properties: value and onChanged. value is a boolean that shows if the checkbox is checked or not. onChanged is a function that updates the state when the user taps the checkbox.

dart
Checkbox(
  value: isChecked,
  onChanged: (bool? newValue) {
    setState(() {
      isChecked = newValue!;
    });
  },
)
Output
A checkbox that toggles between checked and unchecked states when tapped.
💻

Example

This example shows a simple Flutter app with a checkbox. When you tap the checkbox, it toggles between checked and unchecked, updating the UI accordingly.

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Checkbox Example')),
        body: Center(
          child: Checkbox(
            value: isChecked,
            onChanged: (bool? newValue) {
              setState(() {
                isChecked = newValue!;
              });
            },
          ),
        ),
      ),
    );
  }
}
Output
A screen with an app bar titled 'Checkbox Example' and a checkbox in the center that toggles checked state when tapped.
⚠️

Common Pitfalls

  • Not managing the checkbox state with a boolean variable causes the checkbox to not update visually.
  • Forgetting to call setState() inside onChanged means the UI won't refresh.
  • Passing a null or non-boolean value to value causes errors.
dart
/* Wrong way: Missing setState, checkbox won't update */
Checkbox(
  value: isChecked,
  onChanged: (bool? newValue) {
    isChecked = newValue!; // UI does not update
  },
);

/* Right way: Use setState to update UI */
Checkbox(
  value: isChecked,
  onChanged: (bool? newValue) {
    setState(() {
      isChecked = newValue!;
    });
  },
);
📊

Quick Reference

Checkbox Properties:

  • value: bool - current checked state
  • onChanged: Function(bool?) - called when user taps
  • activeColor: Color - color when checked
  • checkColor: Color - color of the check mark

Key Takeaways

Use the Checkbox widget with a boolean value to show checked state.
Update the checkbox state inside setState() to refresh the UI.
The onChanged callback handles user taps and provides the new value.
Always initialize the boolean state variable to avoid null errors.
Customize colors with activeColor and checkColor properties.