How to Make Checkbox Dynamically retrieve data from Mysql?

I want to make checkbox flutter dynamically which retrieve data from database mysql. So, this code can display data from mysql. But still can’t check one by one. this my code :

    class TambahDataTanaman extends StatefulWidget {
      @override
      _TambahDataTanamanState createState() => _TambahDataTanamanState();
    }

    class _TambahDataTanamanState extends State<TambahDataTanaman> {
      GlobalKey<FormState> addTanamanKey = GlobalKey<FormState>();
     
      bool selected = false;
      Future<List> getData() async {
        final response =
            await http.get("http://192.168.1.9/tanampedia/tanahtampil.php");
        return json.decode(response.body);
      }

      List selectedData = [];


      @override


      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text("Tambah Data Tanaman"),
              backgroundColor: Colors.green,
            ),
            body: SingleChildScrollView(
              child: Form(
                key: addTanamanKey,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: ListView(
                    shrinkWrap: true,
                    children: [
                      new Column(
                        children: [
                          new FutureBuilder<dynamic>(
                              future: getData(),
                              builder: (context, snapshot) {
                                if (snapshot.hasError) print(snapshot.error);
                                return snapshot.hasData
                                    ? ListView.builder(
                                        shrinkWrap: true,
                                        itemCount: snapshot.data.length,
                                        itemBuilder: (context, index) {
                                          //List list = snapshot.data;
                                          return CheckboxListTile(
                                            title:
                                                Text(snapshot.data[index]['nama']),
                                            value: selected,
                                            onChanged: (bool newSelected) {
                                              setState(() {
                                                selected = newSelected;
                                              });
                                            },
                                            dense: true,
                                          );
                                        })
                                    : new Center(
                                        child: new CircularProgressIndicator());
                              }),

                         
                          new RaisedButton(
                              child: new Text(
                                "Tambah Data",
                                style: TextStyle(color: Colors.white),
                              ),
                              color: Colors.green,
                              onPressed: () {}),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ));
      }
    }

I use future builder to make list for my checkboxlist. But when running the code, The result of the code above is that all values ​​are checked at the same time, so how to make them correct?
1 Like

Hello ! Have you solution please ??

@Ines_Taleb In the above code the boolean selected is defined globally, the scope is not specific to each data point that’s why all checkboxes get highlighted at once because they all refer to the same value.

Firstly snapshot.data[index] should be taken into a Map variable, and a key named ‘selected’ should be added. And that value should be modified on check and uncheck.

Define a variable called List<Map> data;

class MyWidget extends StatefulWidget {
  State<MyWidget> createState() => MyWidgetState();
}

class MyWidgetState extends State<MyWidget> {
  List<Map> data = [
    {'name': 'Hello'},
    {'name': 'Hello2'},
    {'name': 'Hello3'},
    {'name': 'Hello4'}
  ];
  @override
  Widget build(BuildContext context) {
    print(data);
    return ListView.builder(
        shrinkWrap: true,
        itemCount: data.length,
        itemBuilder: (context, index) {
          return CheckboxListTile(
            title: Text(data[index]['name']),
            value: data[index]['selected'] ?? false,
            onChanged: (bool? newSelected) {
              setState(() {
                data[index]['selected'] = newSelected;
              });
            },
            dense: true,
          );
        });
  }
}

HTH
Sakina