简体   繁体   中英

Why are my checkboxes unchecking themselves after a second on Flutter?

This is what it is supposed to happen:

I have several categories of the Month class that inside them have a list of instances of the FileCell class and Month has a bool checked property that when changes, also changes the bool toTransfer property of every FileCell in its list. Both of these properties are originally set to false.

The checkboxes represent these 'check' and 'toTransfer' properties, but after a second of clicking on them and them changing, they change back to false.

My objective would be: I click on them and they stay put, but that's not happening anymore. Anyone to help me figure this out?

And yes, I'm new to flutter.

PS: (Ignore the portuguese part)

 @override Widget build(BuildContext context) { SessionTimer sessionTimer = SessionTimer(); sessionTimer.startTimer(); return loading ? Loading(status: statusMessage) : Container( child: Scaffold( appBar: AppBar( title: const Text("Meus ficheiros"), ), backgroundColor: Colors.white, body: Column( children: [ Container( child: ButtonBar( alignment: MainAxisAlignment.spaceEvenly, children: [ TextButton.icon( icon: const Icon(Icons.refresh), label: const Text("Reiniciar"), onPressed: (){ setState(() {}); //setState(() => futureFiles = _storage.getAllUserFiles(user.uid)); }, ), TextButton.icon( icon: const Icon(Icons.add), label: const Text("Enviar"), onPressed: (){ UploadFile(); }, ), TextButton.icon( icon: const Icon(Icons.download), label: const Text("Transferir"), onPressed: (){ setState(() {visCheckBoxes = !visCheckBoxes;}); }, ), ], ), decoration: const BoxDecoration( borderRadius: BorderRadius.only( bottomRight: Radius.circular(18), bottomLeft: Radius.circular(18), ), gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [0.8,1], colors: [ Colors.black, Colors.transparent, ], ) ), ), Visibility( visible: visCheckBoxes, child: Column( children: [ Padding( padding: const EdgeInsets.only(top:8.0), child: const Text("Selecione os ficheiros para transferência", style: TextStyle(fontSize: 18)), ), ColoredBox(color: Colors.black, child: Container(height: 1)), ], ), ), Expanded( child: FutureBuilder<ListResult>( future: _storage.getAllUserFiles(user.uid), builder: (BuildContext context,AsyncSnapshot<ListResult> snapshot) { if (snapshot.hasData ) { //List<Reference> files = List<Reference>.empty(growable: true); if(snapshot.data!=null){ if(loading){ setState(() { loading = false; statusMessage = ""; }); } allUserFiles = snapshot.data!.items; if(allUserFiles.isEmpty){ return const Center( child: Text( "Não existem ficheiros na sua área" ) ); } return FutureBuilder<List<Month>>( future: SeparateLists(allUserFiles), builder: (BuildContext context,AsyncSnapshot<List<Month>> snapshot) { if(snapshot.hasData){ if(loading){ setState(() { loading = false; statusMessage = ""; }); } listsByMonth = snapshot.data!; //List of months return ListView.builder( itemCount: listsByMonth.length, itemBuilder: (context, indexMonth) { //TODO Fix check boxes Month month = listsByMonth[indexMonth]; return ExpansionTile( title: visCheckBoxes? Row( children: [ Text(month.name), Checkbox( value: listsByMonth[indexMonth].checked, onChanged: (value){ if(value!=null) { setState(() => listsByMonth[indexMonth].checked = value); } }), ], ) : Text(month.name), initiallyExpanded: true, children: [ //List of the files uploaded in that month Padding( padding: const EdgeInsets.only(left:10.0), child: ListView.builder( key: new Key("list_${month.name}"), shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: month.files.length, itemBuilder: (context, indexFile) { FileCell fileCell = month.files[indexFile]; return ListTile( title: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("${fileCell.name}"), Padding( padding: const EdgeInsets.only(left:8.0), child: Text(DateFormat('dd-MM-yyyy – kk:mm').format(fileCell.timeCreated!)), ), ], ), trailing: visCheckBoxes? Checkbox( value: month.files[indexFile].toTransfer, onChanged: (value)=>{ if(value!=null) setState(()=>listsByMonth[indexMonth].files[indexFile].toTransfer = value), }, ) : null, subtitle: fileCell.downloadProgress != null ? LinearProgressIndicator( valueColor: const AlwaysStoppedAnimation<Color>(Colors.greenAccent), value: fileCell.downloadProgress, ): null, ); }, ), ) ], ); }, ); } return Loading(status: "A carregar os ficheiros"); }, ); } else{ setState(() { statusMessage = "A carregar os ficheiros"; loading = true; }); //setState(()=> loading = true); return Stack(); } } else if (snapshot.hasError) { return const Center( child: Text("Ocorreu um erro a carregar os ficheiros")); } else { return Stack(); } } ), ), ], ),

sessionTimer.startTimer();

return loading
    ? Loading(status: statusMessage)
    : Container(
        child: Scaffold(
            appBar: AppBar(
              title: const Text("Meus ficheiros"),
            ),
            backgroundColor: Colors.white,
            body: Column(
              children: [
                Container(
                  child: ButtonBar(
                    alignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      TextButton.icon(
                          icon: const Icon(Icons.refresh),
                          label: const Text("Reiniciar"),
                          onPressed: (){
                            setState(() {});
                            //setState(() => futureFiles = _storage.getAllUserFiles(user.uid));
                          },
                      ),
                      TextButton.icon(
                          icon: const Icon(Icons.add),

                          label: const Text("Enviar"),
                        onPressed: (){
                          UploadFile();
                        },
                      ),
                      TextButton.icon(
                          icon: const Icon(Icons.download),
                          label: const Text("Transferir"),
                        onPressed: (){
                          setState(() {visCheckBoxes = !visCheckBoxes;});
                        },
                      ),
                    ],
                  ),

                  decoration: const BoxDecoration(
                  borderRadius: BorderRadius.only(
                      bottomRight: Radius.circular(18),
                      bottomLeft: Radius.circular(18),
                  ),
                  gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      stops: [0.8,1],
                      colors: [
                        Colors.black,
                        Colors.transparent,
                      ],
                    )
                  ),
                ),
                Visibility(
                  visible: visCheckBoxes,
                  child: Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(top:8.0),
                        child: const Text("Selecione os ficheiros para transferência", style: TextStyle(fontSize: 18)),
                      ),
                      ColoredBox(color: Colors.black, child: Container(height: 1)),
                    ],
                  ),
                ),
                Expanded(
                    child: FutureBuilder<ListResult>(
                        future: _storage.getAllUserFiles(user.uid),
                        builder: (BuildContext context,AsyncSnapshot<ListResult> snapshot) {
                            if (snapshot.hasData ) {
                              //List<Reference> files = List<Reference>.empty(growable: true);
                              if(snapshot.data!=null){
                                if(loading){
                                  setState(() {
                                    loading = false;
                                    statusMessage = "";
                                  });
                                }
                                allUserFiles = snapshot.data!.items;
                                if(allUserFiles.isEmpty){
                                  return const Center(
                                    child: Text( "Não existem ficheiros na sua área" )
                                  );
                                }
                                return FutureBuilder<List<Month>>(
                                  future: SeparateLists(allUserFiles),
                                  builder: (BuildContext context,AsyncSnapshot<List<Month>> snapshot) {

                                    if(snapshot.hasData){
                                      if(loading){
                                        setState(() {
                                          loading = false;
                                          statusMessage = "";
                                        });
                                      }
                                      listsByMonth = snapshot.data!;

                                      //List of months
                                      return ListView.builder(
                                        itemCount: listsByMonth.length,
                                        itemBuilder: (context, indexMonth) {
                                          //TODO Fix check boxes
                                          Month month = listsByMonth[indexMonth];

                                          return ExpansionTile(
                                            title: visCheckBoxes? Row(
                                              children: [
                                                Text(month.name),
                                                Checkbox(
                                                    value: listsByMonth[indexMonth].checked,
                                                    onChanged: (value){
                                                      if(value!=null) {
                                                        setState(() => listsByMonth[indexMonth].checked = value);
                                                      }
                                                    }),
                                              ],
                                            ) : Text(month.name),

                                            initiallyExpanded: true,
                                            children: [
                                              //List of the files uploaded in that month
                                              Padding(
                                                padding: const EdgeInsets.only(left:10.0),
                                                child: ListView.builder(
                                                  key: new Key("list_${month.name}"),
                                                  shrinkWrap: true,
                                                  physics: const NeverScrollableScrollPhysics(),
                                                  itemCount: month.files.length,
                                                  itemBuilder: (context, indexFile) {
                                                    FileCell fileCell = month.files[indexFile];
                                                    return ListTile(
                                                      title: Column(
                                                        mainAxisAlignment: MainAxisAlignment.start,
                                                        crossAxisAlignment: CrossAxisAlignment.start,
                                                        children: [
                                                          Text("${fileCell.name}"),
                                                          Padding(
                                                            padding: const EdgeInsets.only(left:8.0),
                                                            child: Text(DateFormat('dd-MM-yyyy – kk:mm').format(fileCell.timeCreated!)),
                                                          ),
                                                        ],
                                                      ),
                                                      trailing: visCheckBoxes? Checkbox(
                                                        value: month.files[indexFile].toTransfer,
                                                        onChanged: (value)=>{
                                                          if(value!=null)
                                                          setState(()=>listsByMonth[indexMonth].files[indexFile].toTransfer = value),
                                                        },
                                                      ) : null,

                                                      subtitle: fileCell.downloadProgress != null
                                                          ? LinearProgressIndicator(
                                                        valueColor: const AlwaysStoppedAnimation<Color>(Colors.greenAccent),
                                                        value: fileCell.downloadProgress,
                                                      ): null,
                                                    );
                                                  },
                                                ),
                                              )
                                            ],
                                          );
                                        },
                                      );
                                    }
                                    return Loading(status: "A carregar os ficheiros");

                                  },
                                );
                              }

on every snapshot the listsByMonth = snapshot.data!; line will rest the list and uncheck the checkbox.

you can define listsByMonth globally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM