2

Am trying to select one or more check boxes from a list of check boxes, i have found that the best option is using the checkBoxListTile widget to implement this.

First i have defined a list and used the widget as follows:

List<String> _texts = ["google.com", "youtube.com", "yahoo.com", "gmail.com"];

      Expanded(
        child: ListView(
          children: _texts
              .map((text) => CheckboxListTile(
                    title: Text(text),
                    value: _isChecked,
                    onChanged: (val) {
                      setState(() {
                        _isChecked = val;
                      });
                    },
                  ))
              .toList(),
        ),
      ),

check boxes are displayed fine but whenever i click one checkbox all are checked, how can i handle choosing one or more check boxes from the list?

Thank you

3 Answers 3

4

Try below code hope its help to you I have try it other way

Only Single Checkbox Selected:

Your List :

List _texts = [
    {
      "value": false,
      "site": "google.com",
    },
    {
      "value": false,
      "site": "youtube.com",
    },
    {
      "value": false,
      "site": "yahoo.com",
    },
    {
      "value": false,
      "site": "gmail.com",
    },
  ];

Your Widget:

Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
        child: Column(
          children: List.generate(
            _texts.length,
            (index) => CheckboxListTile(
              controlAffinity: ListTileControlAffinity.leading,
              contentPadding: EdgeInsets.zero,
              dense: true,
              title: Text(
                _texts[index]["site"],
                style: const TextStyle(
                  fontSize: 16.0,
                  color: Colors.black,
                ),
              ),
              value: _texts[index]["value"],
              onChanged: (value) {
                setState(() {
                  for (var element in _texts) {
                    element["value"] = false;
                  }
                  _texts[index]["value"] = value;
                });
              },
            ),
          ),
        ),
      ),

Full Code:

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("Flutter Single Checkbox Example"),
          ),
          body: SafeArea(
              child: Center(
            child: CheckboxWidget(),
          ))),
    );
  }
}

class CheckboxWidget extends StatefulWidget {
  @override
  CheckboxWidgetState createState() => new CheckboxWidgetState();
}

class CheckboxWidgetState extends State {
  List _texts = [
    {
      "value": false,
      "site": "google.com",
    },
    {
      "value": false,
      "site": "youtube.com",
    },
    {
      "value": false,
      "site": "yahoo.com",
    },
    {
      "value": false,
      "site": "gmail.com",
    },
  ];
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
      child: Column(
        children: List.generate(
          _texts.length,
          (index) => CheckboxListTile(
            controlAffinity: ListTileControlAffinity.leading,
            contentPadding: EdgeInsets.zero,
            dense: true,
            title: Text(
              _texts[index]["site"],
              style: const TextStyle(
                fontSize: 16.0,
                color: Colors.black,
              ),
            ),
            value: _texts[index]["value"],
            onChanged: (value) {
              setState(() {
                for (var element in _texts) {
                  element["value"] = false;
                }
                _texts[index]["value"] = value;
              });
            },
          ),
        ),
      ),
    );
  }
}

Result Screen-> image

Multiple Checkbox Selection

Your List/Map

  Map<String, bool> values = {
    'google.com': false,
    'youtube.com': false,
    'yahoo.com': false,
    'gmail.com': false,
  };

Your Function:

  var tmpArray = [];  
  getCheckboxItems() {
    values.forEach((key, value) {
      if (value == true) {
        tmpArray.add(key);
      }
    });

    print(tmpArray);
    tmpArray.clear();
  }

Your Widget:

Column(
      children: <Widget>[
          ListView(
            shrinkWrap: true,
            children: values.keys.map((String key) {
              return new CheckboxListTile(
                title: new Text(key),
                value: values[key],
                onChanged: (value) {
                  setState(() {
                    values[key] = value!;
                  });
                },
              );
            }).toList(),
          
        ),
        const SizedBox(
          height: 100,
        ),
        ElevatedButton(
          child: Text(
            " Checkbox Items ",
            style: TextStyle(fontSize: 18),
          ),
          onPressed: getCheckboxItems,
        ),
      ],
    )

Full Example

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("Flutter Multiple Checkbox Example"),
          ),
          body: SafeArea(
              child: Center(
            child: CheckboxWidget(),
          ))),
    );
  }
}

class CheckboxWidget extends StatefulWidget {
  @override
  CheckboxWidgetState createState() => new CheckboxWidgetState();
}

class CheckboxWidgetState extends State {
  Map<String, bool> values = {
    'google.com': false,
    'youtube.com': false,
    'yahoo.com': false,
    'gmail.com': false,
  };

  var tmpArray = [];

  getCheckboxItems() {
    values.forEach((key, value) {
      if (value == true) {
        tmpArray.add(key);
      }
    });

    print(tmpArray);
    tmpArray.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
          ListView(
            shrinkWrap: true,
            children: values.keys.map((String key) {
              return new CheckboxListTile(
                title: new Text(key),
                value: values[key],
                onChanged: (value) {
                  setState(() {
                    values[key] = value!;
                  });
                },
              );
            }).toList(),
          
        ),
        const SizedBox(
          height: 100,
        ),
        ElevatedButton(
          child: Text(
            " Checkbox Items ",
            style: TextStyle(fontSize: 18),
          ),
          onPressed: getCheckboxItems,
        ),
      ],
    );
  }
}

Result Screen-> image

Refer Video Tutorial for Flutter Multiselect Dropdown Checkbox on YouTube

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this detailed answer that solved my problem and gave new idea, but can i ask what is the elevated button job here? does it print the check box values ?
@editix Yes, Elevated Button Print the selected checkbox value from list
1
import 'package:flutter/material.dart';

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

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: _title,
      home: CheckBoxExample(),
    );
  }
}

class CheckBoxExample extends StatefulWidget {
  const CheckBoxExample({Key? key}) : super(key: key);

  @override
  State<CheckBoxExample> createState() => _CheckBoxExampleState();
}

class _CheckBoxExampleState extends State<CheckBoxExample> {
  String selectedMonth = "";
  List checkListItems = [
    {
      "id": 0,
      "value": false,
      "monthName": "January",
    },
    {
      "id": 1,
      "value": false,
      "monthName": "Febuary",
    },
    {
      "id": 2,
      "value": false,
      "monthName": "March",
    },
    {
      "id": 3,
      "value": false,
      "monthName": "April",
    },
    {
      "id": 4,
      "value": false,
      "monthName": "May",
    },
    {
      "id": 5,
      "value": false,
      "monthName": "June",
    },
    {
      "id": 6,
      "value": false,
      "monthName": "July",
    },
    {
      "id": 7,
      "value": false,
      "monthName": "August",
    },
    {
      "id": 8,
      "value": false,
      "monthName": "September",
    },
    {
      "id": 9,
      "value": false,
      "monthName": "October",
    },
    {
      "id": 10,
      "value": false,
      "monthName": "November",
    },
    {
      "id": 11,
      "value": false,
      "monthName": "December",
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
        child: Column(
          children: [
            Text(
              selectedMonth,
              style: const TextStyle(
                fontSize: 20.0,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 85.0),
            Column(
              children: List.generate(
                checkListItems.length,
                (index) => CheckboxListTile(
                  controlAffinity: ListTileControlAffinity.leading,
                  contentPadding: EdgeInsets.zero,
                  dense: true,
                  title: Text(
                    checkListItems[index]["monthName"],
                    style: const TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                    ),
                  ),
                  value: checkListItems[index]["value"],
                  onChanged: (value) {
                    setState(() {
                      for (var element in checkListItems) {
                        element["value"] = false;
                      }
                      checkListItems[index]["value"] = value;
                      selectedMonth ="${checkListItems[index]["id"]+1}, ${checkListItems[index]["monthName"]}";
                    });
                  },
                ),
              ),
            ),          
          ],
        ),
      ),
    );
  }
}

Output

enter image description here

Comments

0

The value parameter for in CheckboxListTile is how widget knows whether checkbox is checked or not. When you give all of them same value, all of their state changes. You can keep a seperate list to keep track of if the specific checkbox is checked.

2 Comments

do you mean whenever i check or unchecked a box i add or remove its value within another list ?, if you can elaborate more using a code ill be thankful
I meant keeping a list of bool for each one of your checklist, setting false initially and updating current state in onChecked method but seems like answers with code have already posted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.