本文介绍了Flutter:在抽屉中选择标记ListTile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将当前页面的 ListTile 标记为选中,但是2天前,我正在寻找一种通用的方法。

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.

我看到了这样的示例,您可以在其中对磁贴进行硬编码ID并使用大小写来知道当前的 Tile 。我的问题是,如果要夸大100个 ListTile s,该怎么办?如何以编程方式将 selected 属性更改为选定的 Tile ?或更真实的例子:我有一个 Drawer ,它在每个发行版中都会改变形状,因此保留带有硬编码ID的代码没有用。我希望您能理解这个主意。

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.

推荐答案

简单创建枚举类,如下所示。

Simple create enum class like below.

enum DrawerSelection { home, favorites, settings}

创建枚举对象并在以下情况下传递预定义值您需要,在我的情况下,我作为选定的ListTile项目通过了。像下面的代码。

Create enum object and pass pre-defined value if you want, in my case i pass home as selected ListTile item. Like below code.

class _MyHomePage extends State<MyHomePage> {
DrawerSelection _drawerSelection = DrawerSelection.home;

然后在ListTile中使用选定的属性并像下面的代码一样更改enum onTap()。

Then in ListTile use selected property and change enum onTap() like below code.

 ListTile(
              selected: _drawerSelection == DrawerSelection.home,
              title: Text('Home'),
              leading: Icon(Icons.home),
              onTap: () {
                Navigator.pop(context);
                setState(() {
                    _drawerSelection = DrawerSelection.home;
                    _currentWidget = MainWidget();
                    _appBarTitle = Text("Home");
                });
              },
            ),
 ListTile(
            selected: _drawerSelection == DrawerSelection.favorites,
            title: Text('Favorites'),
            leading: Icon(Icons.favorite),
            onTap: () {
              Navigator.pop(context);
              setState(() {
                  _drawerSelection = DrawerSelection.favorites;
                  _currentWidget = FavoritesWidget();
                  _appBarTitle = Text("Favorites");
              });
            },
          ),
ListTile(
            selected: _drawerSelection == DrawerSelection.settings,
            title: Text('Settings'),
            leading: Icon(Icons.settings),
            onTap: () {
              Navigator.pop(context);
              setState(() {
                  _drawerSelection = DrawerSelection.settings;
                  _currentWidget = SettingsWidget();
                  _appBarTitle = Text("Settings");
              });
            },
          ),

这篇关于Flutter:在抽屉中选择标记ListTile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 19:36