FlutterProgramming

How to Use Checkbox and CheckboxListTile in Flutter

Checkboxes are a common user interface element in mobile apps. They are used to allow users to select one or more options from a list of choices. So I am come up with how to use Checkbox and CheckboxListTile widgets in Flutter. 

Where to use checkboxes in the mobile app?

Here are some common use cases for checkboxes in mobile apps:

  • Settings screens: Checkboxes are commonly used in settings screens to allow users to toggle certain features on or off. For example, you might use a checkbox to allow users to turn on or off notifications for your app.
  • Forms: It is often used in forms to allow users to select multiple options. For example, you might use checkboxes to allow users to select multiple items from a list of available options.
  • Surveys: It is also commonly used in surveys to allow users to select multiple answers to a question. For example, you might use checkboxes to allow users to select all of the activities they enjoy doing in their free time.
  • To-Do Lists: It is also used in to-do lists to allow users to mark tasks as completed. This helps users keep track of what tasks they have completed and what tasks still need to be done.

In short, checkboxes are versatile user interface elements that can be used in a variety of ways in mobile apps. They make it easy for users to select one or more options from a list of choices and help to make the user interface more intuitive and user-friendly.


How to Use Checkbox in Flutter

To use the Checkbox widget in Flutter, follow these steps:

1) Create a stateful widget that holds the state of the checkbox. In this example, we’ll create a stateful widget named “MyCheckbox” that holds a boolean value for the checkbox.

 
Dart
class MyCheckbox extends StatefulWidget {
  @override
  State<MyCheckbox> createState() => _MyCheckboxState();
}

class _MyCheckboxState extends State<MyCheckbox> {
  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Checkbox(
      value: _isChecked,
      onChanged: (value) {
        setState(() {
          _isChecked = value!;
        });
      },
    );
  }
}

2) Create an instance of the MyCheckbox widget in your app and add it to your widget tree.

Dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'IntendStuff Checkbox',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Checkbox Demo'),
        ),
        body: Center(
          child: MyCheckbox(),
        ),
      ),
    );
  }
}

3) Run your app and test the MyCheckbox by tapping on it.

You should explore the Checkbox class properties to customize it more.


How to Use CheckboxListTile in Flutter

1) Declare a CheckboxModel class that stores the title of the list tile and the value. You can create model class from here.

Dart
class CheckboxModel {
  String? title;
  bool? value;

  CheckboxModel({this.title, this.value});

  CheckboxModel.fromJson(Map<String, dynamic> json) {
    title = json['title'];
    value = json['value'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['title'] = title;
    data['value'] = value;
    return data;
  }
}

2) Create a stateful widget that holds the state of the checkbox. In this example, we’ll create a stateful widget named “MyCheckboxListTile” that holds a CheckboxModel for the checkbox that contains the both title and its boolean value.

Dart
class MyCheckboxListTile extends StatefulWidget {
  final CheckboxModel? model;

  const MyCheckboxListTile({Key? key, required this.model}) : super(key: key);

  @override
  State<MyCheckboxListTile> createState() => _MyCheckboxListTileState();
}

class _MyCheckboxListTileState extends State<MyCheckboxListTile> {
  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      title: Text(widget.model!.title!),
      value: widget.model!.value,
      onChanged: (value) {
        setState(() {
          widget.model!.value = value!;
        });
      },
      controlAffinity: ListTileControlAffinity.leading,
    );
  }
}

3) Create an instance of the MyCheckboxListTile widget in your app and add it to your widget tree.

Dart
class HomeScreen extends StatelessWidget {
  final List<CheckboxModel> todo = [
    CheckboxModel(title: "eat", value: false),
    CheckboxModel(title: "code", value: false),
    CheckboxModel(title: "sleep", value: false),
    CheckboxModel(title: "repeat", value: false),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Hello IntendStuffers"),
        backgroundColor: const Color(0xff0669FF),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ListView.builder(
              shrinkWrap: true,
              itemCount: todo.length,
              itemBuilder: (context, index) => MyCheckboxListTile(
                model: todo[index],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

4) Run your app and test the MyCheckboxListTile by tapping on it.

You should explore the CheckboxListTile class properties that will help you to customize your widgets.

That’s it! You now know how to use Checkbox and CheckboxListTile widgets in Flutter. Check out our other blog post related to flutter and programming.

Also Read:  3 Easy Steps to Hide Debug Banner in Flutter

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button