skip to Main Content

i have code that helps me dynamically create checkbox buttons from data in my api , now I need a way to help change the state of the check box values when i tap or untap them ,how can go about doing this –

                           for (int i = 0; i < data.names.length;i++)  
                          CheckboxListTile(
                              title: Text(data.names[i]),
                              value: false,
                              onChanged: (value) {
                                
                              })

2

Answers


  1. Just use a variable and update it every time to change the checkbox.

    bool checkBoxSelected = false;
    

    In your onChange you set it to the current value and update your ui.

    setState((){
    checkBoxSelected = value;
    });
    

    And set the current value of your checkbox to the variable (so it isn’t false every time):

    value: checkBoxSelected,
    
    Login or Signup to reply.
  2. i have create demo code as per your requirement ant try this demo:

    import 'package:flutter/material.dart';
    
    class CheckBoxScreen extends StatefulWidget {
      const CheckBoxScreen({super.key});
    
      @override
      State<CheckBoxScreen> createState() => _CheckBoxScreenState();
    }
    
    class _CheckBoxScreenState extends State<CheckBoxScreen> {
      List<bool> checkboxValues = [];
      Map<String, bool> checkboxMap = {};
    
      @override
      void initState() {
        super.initState();
    
        for (int i = 0; i < data.names.length; i++) {
          String name = data.names[i];
          checkboxValues.add(false);
          checkboxMap[name] = false;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Checkbox App'),
          ),
          body: ListView.builder(
            itemCount: data.names.length,
            itemBuilder: (context, index) {
              return CheckboxListTile(
                title: Text(data.names[index]),
                value: checkboxValues[index],
                onChanged: (value) {
                  setState(() {
                    checkboxValues[index] = value ?? false;
                    checkboxMap[data.names[index]] = value ?? false;
                  });
                },
              );
            },
          ),
        );
      }
    }
    
    class DataModel {
      List<String> names;
      DataModel({required this.names});
    }
    
    DataModel data = DataModel(
      names: [
        'Name 1',
        'Name 2',
        'Name 3',
        'Name 4',
        'Name 5',
      ],
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search