在Flutter中选择后更改ListTile的背景颜色

问题描述 投票:10回答:4

我在Flutter制作了一个ListView,但现在我在这个ListTiles中有一些可以选择的ListView。选择后,我希望背景颜色更改为我选择的颜色。我不知道该怎么做。在the docs他们提到ListTile有一个属性style。但是,当我尝试添加它时(如下面代码中的第三行),这个style属性在下面得到一条波浪形的红线,编译器告诉我The named parameter 'style' isn't defined

Widget _buildRow(String string){
  return new ListTile(
    title: new Text(string),
    onTap: () => setState(() => toggleSelection(string)),
    selected: selectedFriends.contains(string),
    style: new ListTileTheme(selectedColor: Colors.white,),
  );
}
listview user-interface dart background-color flutter
4个回答
7
投票

这不是具有ListTile属性的style。但是ListTileThemeListTileTheme是一个inheritedWidget。和其他人一样,它用于传递数据(例如主题)。

要使用它,您必须使用包含所需值的ListTileTheme将任何窗口小部件包装在ListTile上方。

然后ListTile将根据最接近的ListTileTheme实例来主题化。


11
投票

如果你还需要一个带有连锁效果的onTap听众,你可以使用Ink

ListView(
  children: [
    Ink(
      color: Colors.lightGreen,
      child: ListTile(
        title: Text('With lightGreen background'),
        onTap() { },
      ),
    ),
  ],
);

Ripple Effect


10
投票

我可以使用Container内的BoxDecoration更改ListTile的背景颜色:

ListView (
    children: <Widget>[
        new Container (
            decoration: new BoxDecoration (
                color: Colors.red
            ),
            child: new ListTile (
                leading: const Icon(Icons.euro_symbol),
                title: Text('250,00')
            )
        )
    ]
)

0
投票

我能够通过使其成为Container Widget的子项并向Container Widget添加颜色来更改ListTile的背景颜色。

这里的drawerItem是保存isSelected值的模型类。背景颜色取决于isSelected值。

注意:对于未选择的项目,请保持颜色透明,这样您仍将获得涟漪效果。

 for (var i = 0; i < drawerItems.length; i++) {
      var drawerItem = drawerItems[i];
      drawerOptions.add(new Container(
        color: drawerItem.isSelected
            ? Colors.orangeAccent
            : Colors.transparent,
        child: new ListTile(
          title: new Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[Text(drawerItem.title), drawerItem.count],
          ),
          leading: SvgPicture.asset(
            drawerItem.icon,
            width: 34,
            height: 34,
          ),
          onTap: () {
            _handleNavigation(i);
          },
          selected: drawerItem.isSelected,
        ),
      ));
    }

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.