I want to mark the ListTile of the current page as selected but 2 days ago I'm looking for a general way to do it.

I saw examples like this one where you hardcode the tile ID and use a case to know which is the current Tile. My question is, what if I have, to exaggerate, 100 ListTiles? How do I change the selected attribute programmatically to the selected Tile? Or a more real case: I have a Drawer that changes shape in each release, so keeping a code with the hardcoded IDs is not useful. I hope you understand the idea.

I've been trying different solutions for days but none seems general enough to me.

Translated with www.DeepL.com/Translator

1 Answers

Community On

i think it is just simple you can create a new class that have your data and the bool selected

    class Post {
      final bool selected;
      var data;


now when you use LIstView.builder in the itemBuilder if list[index].selected is true then set the color to blue if not then let it white or whatever in the on tap or onpressed whatever you are you using save the last clicked index in a global variable(called savedIndex)-initialize it with (-1)- and change selected to true at the this list index,then if savedIndex wasnt equal -1 change list[savedIndex].selected=false.

global variable

int selectedIndex =-1;

and itemBuilder.

itemBuilder: (BuildContext _context, int i) {

        return GestureDetector(

                  decoration: new BoxDecoration(
                    borderRadius: new BorderRadius.circular(16.0),
                    color:_list[index].selected? Colors.blue:colors.white,
                  child: _buildRow(_list[index]),) ,
                onTap: () {