Home > database >  Select single checkbox using checkBoxListTile - Flutter
Select single checkbox using checkBoxListTile - Flutter

Time:12-22

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related