List values in PHP with Checkboxlisttitle and set an id for each checkbox listed

Asked

Viewed 47 times

0

I am listing some values that are returned from a PHP API. In this list I am using a Checkbox for each information.

When I click on any Checkbox, all items in the list are selected. How do I pick a specific item?

Follow the code below:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class ListaCNPJ extends StatefulWidget {

  String cpf;
  String perfil;


  ListaCNPJ({this.cpf, this.perfil});

  @override
  _ListaCNPJState createState() => _ListaCNPJState();
}

class _ListaCNPJState extends State<ListaCNPJ> {

  bool _lista = false;
  //TextEditingController _controllerCNPJ = TextEditingController();

  Future getContactData(String cpf, String perfil) async {
    const URL = 'http://localhost/camera/api.php';
    var response = await http.get(
        URL + "?action=consultarCNPJ"
            "&cpf=$cpf"
            "&perfil=$perfil"
    );

    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Lista de CNPJs"),
        centerTitle: true,
      ),
      body: FutureBuilder(
        future: getContactData(widget.cpf, widget.perfil),
        builder: (context, snapshot){
          print("resposta: "+snapshot.data.toString());
          if(snapshot.hasError){
            print(snapshot.error);
          }

          return snapshot.hasData ? Column(
            children: [
              Expanded(
                  child: ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index){
                    List list = snapshot.data;
                    return ListTile(
                        title: CheckboxListTile(
                            title: Text(list[index]['tb_empresa']),
                            subtitle: Text(list[index]['tb_cnpj']),
                            value: false, // _lista[index]["realizada"],
                            onChanged: (valor){
                              setState(() {
                                _lista = valor;
                              });


                            },
                        )
                    );
                  }
                )
              )
            ],
          ) :
          Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

1 answer

0

All of its Checkbox are with the same behavior because what will dictate their state is the value you put on the property value: false,.

That is, what will tell you if the Checkbox is checked or unchecked is the value that is placed in this property. If you use the same value _lista For everyone, they’re all going to behave the same. The very name of the variable "list" you gave indicates that whoever wrote it might have already thought about it.

There are several ways to solve your problem. I leave here the simplest I could think of:

  • Create a variable that will group a list of booleans representing the state of each Checkbox:
List<bool> _lista;
  • When you receive your information, fill in your list with an initial amount (for example false) for each Checkbox:
builder: (context, snapshot){
      if (snapshot.hasData){
          _lista = List<bool>.filled(snapshot.data.length, false);
      }
[...]

That will make a list in the following form: [false,false,false...].

  • Use this information when creating Checkbox’s:
value: _lista[index],
  • And by changing them too:
onChanged: (valor){
                       setState(() {
                           _lista[index] = valor;
                       });
                   },

Finally, its Futurebuilder is calling this function getContactData every time the screen is redesigned. By official documentation we can read:

The Future must have been obtained earlier, e.g. During State.initState, State.didUpdateWidget, or State.didChangeDependencies.

That is, that Future used must be obtained before, and stored in the variable to be used in Futurebuilder:

Future retornoDaApi;

and in initState the call to the API is started and the return is stored in this variable:

@override
initState() {
  super.initState();
  retornoDaApi = getContactData(widget.cpf, widget.perfil);
}

For Futurebuilder to use the Future of this variable:

future:retornoDaApi,

For more information I suggest reading the links listed, which are part of the official documentation, about Checkbox and Futurebuilder.

  • I tried this way but got this error The getter 'length' was called on null. Receiver: null Tried Calling: length, I believe it is in the assignment of List below Future: retornoDaApi, Builder: (context, snapshot){ _list = List<bool>. (snapshot.data.length, false); // print("reply: "+snapshot.data.length.toString()); if(snapshot.hasError){ print(snapshot.error); }

  • @test Oh yes. You need to check if the snapshot has data before. You’ve done this in code, something like if(snapshot.hasData) { _list = List<bool>.filled(snapshot.data.length, false);}. I’ll edit the answer to include this.

  • the error Gone but the checkbox is not checking, I printed the variable _list[index] is returning true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.