Create Checkbox Options in Flutter with Dart

Tiempo de lectura: < 1 minuto

In this example, I’m going to show you how to create a set of checkbox options in Flutter using the Dart programming language.

To do this, we’ll create a component that we’ll call CheckboxGroup. This component will have its properties and events to handle the selection of options, allowing us to use it in any view or widget.

class CheckboxGroup extends StatefulWidget {
  final List<String> options;
  final ValueChanged<List<String>> onChanged;

  CheckboxGroup({required this.options, required this.onChanged});

  @override
  _CheckboxGroupState createState() => _CheckboxGroupState();
}

class _CheckboxGroupState extends State<CheckboxGroup> {
  List<String> _selectedOptions = [];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: widget.options.map((String value) {
        return CheckboxListTile(
          title: Text(value),
          value: _selectedOptions.contains(value),
          onChanged: (bool? checked) {
            setState(() {
              if (checked != null && checked) {
                _selectedOptions.add(value);
              } else {
                _selectedOptions.remove(value);
              }
              widget.onChanged(_selectedOptions);
            });
          },
        );
      }).toList(),
    );
  }
}

Now, in the MyApp view, we’ll use this CheckboxGroup component we just created as shown below.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Checkbox Example for DevCodeLight'),
        ),
        body: Center(
          child: CheckboxGroup(
            options: ['Option 1', 'Option 2', 'Option 3'],
            onChanged: (selected) {
              print('Selected: $selected');
            },
          ),
        ),
      ),
    );
  }
}

Finally, below we see the result of the complete example.

I hope it helps you. Have a great day!

Leave a Comment