Lix
Lix

Reputation: 471

Flutter: How to get values of a checkbox and put in a variable

I'm currently stuck on a code in flutter.

So, I have a checkbox and I want that everytime I click the checkbox the value of that checkbox will be save in an array variable and if I click it again the value will be removed in the array variable, so in that way I can call that array variable and save it in the database.

This is what I have so far.

My code:

Map<String, bool> values = {
'Food': false,
'Materials': false,
};

Widget build(BuildContext context) {
return Scaffold(
  appBar: new AppBar(title: new Text('CheckboxListTile demo')),
  body:  new ListView(
    children: values.keys.map((String key) {
      return new CheckboxListTile(
        title: new Text(key),
        value: values[key],
        onChanged: (bool value) {
          setState(() {
            values[key] = value;
          });
          print(key);
         },
       );
      }).toList(),
     ),
   );
  }
 }

My UI:

enter image description here

Upvotes: 2

Views: 12785

Answers (2)

knikhilesh
knikhilesh

Reputation: 11

//calling in main funtion

void main(){

runApp(GridCheck1());

}

//code

import 'package:flutter/material.dart';

class GridCheck1 extends StatelessWidget{

  @override

  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('List Checkbox Demo'),
        ),
        body: MyGridCheckDemo(),
      ),
    );

  }
}

class MyGridCheckDemo extends StatefulWidget {
  @override
  _MyGridCheckState createState() => _MyGridCheckState();
}

class _MyGridCheckState extends State<MyGridCheckDemo> {
  var selectedItem;
  bool selecteValue = false;

  List<GridCheckModel> checkBoxListTileModel = GridCheckModel.getUsers();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueGrey,
        centerTitle: true,
        title:  Text(
          'CheckBox ListTile Demo',
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Column(
        children: [
          Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 10),
            child: Text('Selected Item: ${selectedItem}'+ ', ' + ' Selected Value: ${selecteValue}', style: TextStyle(fontSize: 20, fontWeight: FontWeight.normal),),

          ),
        Expanded(
            child: GridView.builder(

                shrinkWrap: true,

                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 4.0,
                  mainAxisSpacing: 4.0,
                ),
                itemCount: 12,

                itemBuilder: (BuildContext context, int index) {


                  return Card(

                    elevation: 20,

                    color: Colors.orange,

                    child: Container(

                      padding: EdgeInsets.all(10.0),

                      child: Column(

                        children: <Widget>[

                          CheckboxListTile(
                            //checkColor: Colors.indigo,
                              tileColor: Colors.greenAccent,
                              controlAffinity: ListTileControlAffinity.trailing,
                              activeColor: Colors.pink[300],
                              dense: true,

                              //font change
                              title: Text(

                                checkBoxListTileModel[index].title,

                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  letterSpacing: 0.5,
                                ),
                              ),
                              value: checkBoxListTileModel[index].isCheck,

                              onChanged: (bool? newValue) {
                                //itemChange(newValue!, index);
                                setState(() {
                                  checkBoxListTileModel[index].isCheck = newValue!;
                                  if(checkBoxListTileModel[index].isCheck) {
                                    selectedItem = checkBoxListTileModel[index].title;
                                    selecteValue =  checkBoxListTileModel[index].isCheck;
                                  }
                                  else{
                                    selectedItem = '';
                                    selecteValue = checkBoxListTileModel[index].isCheck!;
                                  }
                                });
                              }
                              ),
                        ],
                      ),
                    ),
                  );
                }
            ),
          )
        ],
      ),
    );
  }

  void itemChange(bool val, int index) {
    setState(() {
      checkBoxListTileModel[index].isCheck = val;
    });
  }
}
class GridCheckModel {
  int userId;
  String title;
  bool isCheck;

  GridCheckModel({required this.userId, required this.title, required this.isCheck});

  static List<GridCheckModel> getUsers() {
    return <GridCheckModel>[

      GridCheckModel(
          userId: 1,
          title: "Android",
          isCheck: false),
      GridCheckModel(
          userId: 2,
          title: "Flutter",
          isCheck: false),
      GridCheckModel(
          userId: 3,
          title: "IOS",
          isCheck: false),
      GridCheckModel(
          userId: 4,
          title: "PHP",
          isCheck: false),
      GridCheckModel(
          userId: 5,
          title: "Node",
          isCheck: false),
      GridCheckModel(
          userId: 6,
          title: "c#",
          isCheck: false),
      GridCheckModel(
          userId: 7,
          title: "C",
          isCheck: false),
      GridCheckModel(
          userId: 8,
          title: "C++",
          isCheck: false),
      GridCheckModel(
          userId: 9,
          title: "React",
          isCheck: false),
      GridCheckModel(
          userId: 10,
          title: "Ruby",
          isCheck: false),
      GridCheckModel(
          userId: 11,
          title: ".Net",
          isCheck: false),
      GridCheckModel(
          userId: 12,
          title: "Cobol",
          isCheck: false),
    ];
  }
}

output:

enter image description here

Upvotes: 1

Ravinder Kumar
Ravinder Kumar

Reputation: 7990

To save your key and values in a list, Declare a model class for title and value,

class MyClass {
  String title;
  bool value;
  MyClass(this.title, this.value);
  @override
  String toString() {
    return 'MyClass{title: $title, value: $value}';
  }
}

Now declare a list with MyClass,

List<MyClass> selecteditems = List();

Now add data like this,

              setState(() {
                values[key] = value;
                selecteditems.clear();
                values.forEach((key, value) {
                  print('${key}: ${value}');
                  if (value) {
                    selecteditems.add(MyClass(key, value));
                  }
                });
              });

To check output print selected inside build method

  @override
  Widget build(BuildContext context) {
    print(selecteditems.toString());

Output 1: 1 item selected

[MyClass{title: Food, value: true}]

enter image description here

Output 2: all items selected

[MyClass{title: Food, value: true}, MyClass{title: Materials, value: true}]

enter image description here

Output 2: all items un-selected'

Nothing will print

Upvotes: 3

Related Questions