Working with dynamic Checkboxes in Flutter

Last updated on October 23, 2020 The Frog Loading... 2 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)

What we will make?

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 in the code ๐Ÿ™‚

Getting Started

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

Check it out:

The complete code (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(),
            )
          ]),
        ),
      ),
    );
  }
}

Related Articles

guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ocetessa
ocetessa
5 months ago

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

A Goodman
Admin
A Goodman
5 months ago
Reply to  ocetessa

Yes, we can do that by using Row. I guess you wanna make a Quiz app ๐Ÿ™‚

Last edited 5 months ago by A Goodman
2
0
Would love your thoughts, please comment.x
()
x