Working with dynamic Checkboxes in Flutter

Last updated on September 21, 2021 A Goodman Loading... 4 comments

This tutorial shows you how to implement dynamic checkboxes in Flutter.

Summary

Which widgets you should use?

  • CheckBox: A material design checkbox
  • CheckboxListTile: A checkbox with a label (we’ll use this one)

Example Preview

We’ll make a small Flutter app that contains some checkboxes (based on a list of available hobbies) that allow the users to choose their hobbies and reflect these choices immediately to the screen.

No more talking, let’s dive into the code.

The Steps

If you want to see the final code instead of going through the steps, just skip this section and move on to the next one.

1. Create a new Flutter project:

flutter create checkbox_example

2. Remove all the default code in the lib/main.dart file and add the following skeleton code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // Generate a list of available hobbies here

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(20),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(
              'Choose your hobbies:',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 10),
            Divider(),
            SizedBox(height: 10),

            // The checkboxes will be here
            
            // Display the result here
            SizedBox(height: 10),
            Divider(),
            SizedBox(height: 10),
           
          ]),
        ),
      ),
    );
  }
}

3. Create the hobby list:

  // Generate a list of available hobbies here
  List<Map> availableHobbies = [
    {
      "name": "Foobball",
      "isChecked": false
    },
    {
      "name": "Baseball",
      "isChecked": false
    },
    {
      "name": "Video Games",
      "isChecked": false, 
    },
    {
      "name": "Readding Books",
      "isChecked": false
    },
    {
      "name": "Surfling The Internet",
      "isChecked": false
    }
  ];

4. Display the checkboxes:

            // The checkboxes will be here
            Column(
                children: availableHobbies.map((hobby) {
              return CheckboxListTile(
                  value: hobby["isChecked"],
                  title: Text(hobby["name"]),
                  onChanged: (newValue) {
                    setState(() {
                      hobby["isChecked"] = newValue;
                    });
                  });
            }).toList()),

5. Display the choice(s):

            // Display the result here
            SizedBox(height: 10),
            Divider(),
            SizedBox(height: 10),
            Wrap(
              children: availableHobbies.map((hobby) {
                if (hobby["isChecked"] == true) {
                  return Card(
                    elevation: 3,
                    color: Colors.amber,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(hobby["name"]),
                    ),
                  ); 
                }

                return Container();
              }).toList(),
            )

6. Launch your iOS simulator or Android emulator then run the following command:

flutter run

The Final Code

Here’s the full source code in main.dart:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // Generate a list of available hobbies here
  List<Map> availableHobbies = [
    {"name": "Foobball", "isChecked": false},
    {"name": "Baseball", "isChecked": false},
    {
      "name": "Video Games",
      "isChecked": false,
    },
    {"name": "Readding Books", "isChecked": false},
    {"name": "Surfling The Internet", "isChecked": false}
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(20),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(
              'Choose your hobbies:',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 10),
            Divider(),
            SizedBox(height: 10),

            // The checkboxes will be here
            Column(
                children: availableHobbies.map((hobby) {
              return CheckboxListTile(
                  value: hobby["isChecked"],
                  title: Text(hobby["name"]),
                  onChanged: (newValue) {
                    setState(() {
                      hobby["isChecked"] = newValue;
                    });
                  });
            }).toList()),

            // Display the result here
            SizedBox(height: 10),
            Divider(),
            SizedBox(height: 10),
            Wrap(
              children: availableHobbies.map((hobby) {
                if (hobby["isChecked"] == true) {
                  return Card(
                    elevation: 3,
                    color: Colors.amber,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(hobby["name"]),
                    ),
                  );
                }

                return Container();
              }).toList(),
            )
          ]),
        ),
      ),
    );
  }
}

Wrap Up

We’ve made a simple mobile app to learn about implementing multiple dynamic checkboxes and the CheckboxListTile widget in Flutter. If you’d like to explore more new things in Flutter and Dart, take a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
4 Comments
Inline Feedbacks
View all comments
Fathima Shafana
Fathima Shafana
4 months ago

In this example list is predefined. How to use checkboxlisttile where list is created dynamically.

ocetessa
ocetessa
10 months ago

Hi, thanks for all. really good.
Can we have and choose more chexboxes in the same line (A-B-C-D)

Related Articles