【问题标题】:How to get to instance in callback如何在回调中获取实例
【发布时间】:2019-07-18 22:50:13
【问题描述】:

我正在尝试在抽屉中的 ListTile 列表中切换选择?

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

【问题讨论】:

    标签: flutter


    【解决方案1】:

    this 指向包含问题中代码的小部件。 您可以在分配ListTile 的位置创建一个变量,然后可以在onTap 中引用它。

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

    最好使用一个值来存储所选项目,例如 itemId,而不是小部件引用。

    【讨论】:

    • 如果使用 itemId,您会保留对带有 itemId 的自定义 ListTile 列表的引用 - 还是使用 Key?
    • 我需要更多的上下文来完全理解你想要完成的事情。我认为您根本不需要对小部件的引用。
    • 谢谢,我只是想让选中的 ListTile 在选中时脱颖而出。我觉得已经有一个解决方案,因为这是一个常见的场景。有人这样做了,但仍然:stackoverflow.com/questions/49331612/…
    • 我想我应该 setState 并重建,如果它只是 ListTile 的重建就好了
    • 是的,如果你想更新UI,你需要setState()
    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2010-10-12
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多