4

I am trying to toggle selected in a list of ListTile in a Drawer?

    ListTile(
      title: Text("Name"),
      leading: Icon(Icons.dashboard),
      onTap: () {
        currentSelected.selected = false
        this.selected = true;
        currentSelected = this; // << How to get the instance of ListTile
      },
    ),
Chris G.
  • 23,930
  • 48
  • 177
  • 302

1 Answers1

1

this points to the widget that contains the code in your question. You can create a variable where you assign the ListTile, then you can reference it in onTap.

ListTile listTile;
listTile = ListTile(
      title: Text("Name"),
      leading: Icon(Icons.dashboard),
      onTap: () {
        currentSelected.selected = false
        this.selected = true;
        currentSelected = listTile
      },
    ),
return listTile;

It would be better to use a value to store the selected item, like an itemId, instead of a widget reference.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • If using itemId, would you then keep a reference to a list of custom ListTile with an itemId - or maybe use Key? – Chris G. Feb 25 '19 at 14:15
  • I would need more context to fully understand what you try to accomplish. I think you shouldn't need a reference to a widget at all. – Günter Zöchbauer Feb 25 '19 at 14:20
  • Thanks, I just want to make the selected ListTile stand out, when selected. I feel like there already is a solution to this, as this a common scenario. One have done this, but still: https://stackoverflow.com/questions/49331612/change-background-color-of-listtile-upon-selection-in-flutter – Chris G. Feb 25 '19 at 14:23
  • I guess I should setState and rebuild, would be nice it it was just a rebuild of ListTile – Chris G. Feb 25 '19 at 14:28
  • Yes, if you want the UI to update, you need `setState()` – Günter Zöchbauer Feb 25 '19 at 14:28