key
key

Reputation: 1404

ListView check-boxes are being checked all at once

I have this ListView.builder with simple Cards, it's build with bloc like so:

   return ListView.builder(
                  itemCount: snapshot.data.documents.length,
                  itemBuilder: (BuildContext context, int index) {

                    var snap = snapshot.data.documents[index];
...

inside this list I have checkboxs like so:

class _MyHomePageState extends State<MyHomePage> {

    bool _isChacked = false;

...

Card(
                                    elevation: 10.0,
                                    child: Container(
                                      width: 60.0,
                                      height: 50.0,
                                      child: Checkbox(
                                        activeColor: Colors.red,
                                          value: _isChacked,
                                          onChanged: (value) {
                                            setState(() {
                                              _isChacked = value;
                                              print(value);
                                            });
                                          },
                                      ),
                                    ),
                                  ),

if I click I get the check-boxes to change value but unfortunately all at onece how do I target everyone on it's own?

I thought about a List or a Map but I do not know how to use it.

also It's not important to hold the state of the check-boxes because saving the value to a db I know but I just need it locally.

Upvotes: 1

Views: 2040

Answers (1)

Nha Phạm Thị
Nha Phạm Thị

Reputation: 419

Because all the checkboxes are depending on the _isChecked value. If you only want checkbox can be toggle, you should use

    List<int> _selected_box = List();
    ...

    child: Checkbox(
             activeColor: Colors.red,
             value: _selected_box.contains(index),//index is the position of the checkbox
             onChanged: (value) {
                  setState(() {
                      // remove or add index to _selected_box
                      if(_selected_box.contains(index)) _selected_box.remove(index);
                      else _selected_box.add(index); 
                      print(index);
                  });
             },
             ),

Upvotes: 3

Related Questions