Home > Net >  How to get the items from list according to id in flutter
How to get the items from list according to id in flutter

Time:11-03

Requirement:

I created a list of days using CheckboxlistTile, and i want when i check any checkbox a button will display, and onclick on button a dialogue will display where user can add time in textfield, and then on click on submit button of dialogue that textfield time input will convert into a tag and will display below the checkbox.

here my screen look like before check the checkbox

enter image description here

initially i set monday checkbox checked.

so when i click on add button (which in at the right of checkbox), this dialogue will display

enter image description here

and when i enter the values and after clicking on submit button, tag will look like this

enter image description here

Problem:

Problem is, when i check the tuesday or any other checkbox this tag is displaying in its list, wherease i have not selected time for tuesday or any checkbox, i guess the problem is in list which i'm passing to create tags _timingTagListForToken

enter image description here

here is the code:

Days list class

class CheckBoxListTileModelForToken {
  int id;
  String title;
  bool isCheck;

  CheckBoxListTileModelForToken({required this.id,required this.title, required this.isCheck});

  static List<CheckBoxListTileModelForToken> getUsers() {
    return <CheckBoxListTileModelForToken>[
    CheckBoxListTileModelForToken(id:1,title: "Monday", isCheck: true,),
    CheckBoxListTileModelForToken(id:2,title: "Tuesday", isCheck: false),
    CheckBoxListTileModelForToken(id:3,title: "Wednesday", isCheck: false),
    CheckBoxListTileModelForToken(id:4,title: "Thursday", isCheck: false),
    CheckBoxListTileModelForToken(id:5,title: "Friday", isCheck: false),
    CheckBoxListTileModelForToken(id:6,title: "Saturday", isCheck: false),
    CheckBoxListTileModelForToken(id:7,title: "Sunday", isCheck: false),
    ];
  }
}

Code where i'm display the Checkboxes

customExpansionTile(context, "Token Distribution Time", 
          true,
            Icon(Icons.timer, color: HexColor("#5344ed")), 
            <Widget>[
            Container(
                child: Row(
              children: [
                Expanded(
                    child: SizedBox(
                        height: MediaQuery.of(context).size.height * 0.45,
                        child: ListTile(
                          title: ListView.builder(
                          itemCount: checkBoxListTileModelForToken.length,
                          itemBuilder: (BuildContext context, int index) {
                          return new Card(
                            child: new Container(
                              padding: new EdgeInsets.all(10.0),
                              child: Column(
                                children: <Widget>[
                                  new CheckboxListTile(
                                      controlAffinity:ListTileControlAffinity.leading,
                                      activeColor: HexColor("#5344ed"),
                                      dense: true,
                                      title: new Text(
                                        checkBoxListTileModelForToken[index].title,
                                        style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w600,
                                            letterSpacing: 0.5),
                                      ),
                                      value: checkBoxListTileModelForToken[index].isCheck? true:false,
                                      secondary:  Container(
                                      alignment:Alignment.centerRight,
                                      height: MediaQuery.of(context).size.height*0.9,
                                      width: MediaQuery.of(context).size.width *0.2,
                                      child:checkBoxListTileModelForToken[index].isCheck ==true?
                                          IconButton(
                                            tooltip:"Pick Time",
                                            onPressed: () {
                                              _tokenTimeDialogue(
                                                  checkBoxListTileModelForToken[index].id);
                                            },
                                            icon: Icon(Icons.add,color: HexColor("#5344ed"),)
                                          )
                                              : null),
                                    onChanged: (bool? val) {
                                 itemChangeforToken(val!, index);
                                    }),
                                    SizedBox10(),
                                    Wrap(
                                      direction:Axis.horizontal,
                                      children:[
                                        Container(
                                      child:checkBoxListTileModelForToken[index].isCheck? Tags(
                                        itemCount:_timingTagListForToken.length,
                                        itemBuilder: (int index){          
                                        return  ItemTags(
                                              key: Key(index.toString()),
                                              activeColor:HexColor("#5344ed"),
                                              index: index, 
                                              title:_timingTagListForToken[index],
                                              textStyle: TextStyle( fontSize: 14, ),
                                              combine: ItemTagsCombine.withTextBefore,
                                              
                                              removeButton: ItemTagsRemoveButton(
                                                backgroundColor:HexColor("#5344ed"),
                                                onRemoved: (){  
                                                    setState(() {
                                                        _timingTagListForToken.removeAt(index);
                                                    });
                                                    return true;
                                                },
                                              ),
                                              onPressed: (item) => print(item),
                                              onLongPressed: (item) => print(item),
                                        );
                                      },):Padding(
                                        padding: const EdgeInsets.only(left: 70),
                                        child:
                                            Row(crossAxisAlignment: CrossAxisAlignment.center, children: []))
                                                                ),
                                      ])]),
                          ),
                        );
                      }),
                  
                      ))),



 itemChangeforToken(bool val, int index) {
  setState(() {
    //id=checkBoxListTileModelForToken[index].id;
      //print("id onchange "  id.toString());
    checkBoxListTileModelForToken[index].isCheck = val;

   
    
  });
  
}


Dialogue code


_tokenTimeDialogue(dynamic id) {
    AlertDialog alert = AlertDialog(
        scrollable: true,
        insetPadding: EdgeInsets.symmetric(vertical: 50),
        title: Text("Add timing of the day",
          style: TextStyle(fontWeight: FontWeight.bold, color: HexColor("#5344ed"))),
        content: Container(
          child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(children: <Widget>[
            textfieldforTimeDialogue(
              context,
              () async {
                    TimeOfDay? pickedTime = await showTimePicker(
                      initialTime: TimeOfDay.now(),
                      context: context,
                      builder:(context, child) {
                            return Theme(
                              data: Theme.of(context).copyWith(
                                colorScheme: ColorScheme.light(
                                  primary: HexColor(
                                      "#6610f2"), // header background color
                                  onPrimary: Colors.black, // header text color
                                  onSurface: Colors.black, // body text color
                                ),
                                textButtonTheme: TextButtonThemeData(
                                  style: TextButton.styleFrom(
                                    primary: HexColor(
                                        "#6610f2"), // button text color
                                  ),
                                ),
                              ),
                              child: child!,
                            );
                          },
                    );
                    if (pickedTime != null) {
                      setState(() {
                        fromTimeForToken.text = pickedTime.format(context);
                      });
                    } else {
                      print("Time is not selected");
                    }
                  },
                  Icons.timer_off,
                  fromTimeForToken,
                  "From",
                  "From",
            ),
            
            SizedBox20(),
            textfieldforTimeDialogue(
              context,
              () async {
                FocusScope.of(context).unfocus();
                    TimeOfDay? pickedTime = await showTimePicker(
                      initialTime: TimeOfDay.now(),
                      context: context,
                       builder:(context, child) {
                            return Theme(
                              data: Theme.of(context).copyWith(
                                colorScheme: ColorScheme.light(
                                  primary: HexColor(
                                      "#6610f2"), // header background color
                                  onPrimary: Colors.black, // header text color
                                  onSurface: Colors.black, // body text color
                                ),
                                textButtonTheme: TextButtonThemeData(
                                  style: TextButton.styleFrom(
                                    primary: HexColor(
                                        "#6610f2"), // button text color
                                  ),
                                ),
                              ),
                              child: child!,
                            );
                          },
                    );
                    if (pickedTime != null) {
                      setState(() {
                        toTimeForToken.text = pickedTime.format(context);
                      });
                    } else {
                      print("Time is not selected");
                    }
                  },
                  Icons.timer_off,
                  toTimeForToken,
                  "To",
                  "To",
            ),
          ]),
        )),
        actions: [
          TextButton(
            
            onPressed: () {
            setState(() {
            fromTimeForToken.text="";
            toTimeForToken.text="";
            });
              Navigator.pop(context);
            },
            child: Text(
              "Submit",
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: HexColor("#5344ed"),
                  fontSize: 20),
            ),
          )
        ]);
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }


please help where i'm doing wrong, how i can do this?

CodePudding user response:

You are right - you handle the tags list wrong. For every Monday, Tuesday etc., you are looping through the entire list.

Something like this should work (I only changed lines 2 and 3 below)

child:checkBoxListTileModelForToken[index].isCheck? Tags(
                                        itemCount:_timingTagListForToken[index]==null?0:1, //show only a single tag for your option
                                        itemBuilder: (int index2){ // here you must rename your variable, since we need access to index in the outer loop          
                                        return  ItemTags(
                                              key: Key(index.toString()),
                                              activeColor:HexColor("#5344ed"),
                                              index: index, 
                                              title:_timingTagListForToken[index],
                                              textStyle: TextStyle( fontSize: 14, ),
                                              combine: ItemTagsCombine.withTextBefore,
                                              
                                              removeButton: ItemTagsRemoveButton(
                                                backgroundColor:HexColor("#5344ed"),
                                                onRemoved: (){  
                                                    setState(() {
                                                        _timingTagListForToken.removeAt(index);
                                                    });
                                                    return true;
                                                },
                                              ),
                                              onPressed: (item) => print(item),
                                              onLongPressed: (item) => print(item),
                                        );
  • Related