I've made a ListView
in Flutter, but now I have some ListTiles
in this ListView
that can be selected. Upon selection, I want the background color to change to a color of my choice. I don't know how to do that.
In the docs they mention that a ListTile
has a property style
. However, when I try to add that (as in third last line in the code below), this style
property gets a squiggly red line underneath and the compiler tells me that 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,),
);
}
It's not ListTile
that has the style
property. But ListTileTheme
.
ListTileTheme
is an inheritedWidget. And like others, it's used to pass down data (such as theme here).
To use it, you have to wrap any widget above your ListTile with a ListTileTheme
containing the desired values.
ListTile
will then theme itself depending on the closest ListTileTheme
instance.
If you also need an onTap
listener with a ripple effect, you can use Ink
:
ListView(
children: [
Ink(
color: Colors.lightGreen,
child: ListTile(
title: Text('With lightGreen background'),
onTap() { },
),
),
],
);
![](https://www.manongdao.com/static/images/pcload.jpg)
I was able to change the background color of the ListTile using a BoxDecoration inside Container:
ListView (
children: <Widget>[
new Container (
decoration: new BoxDecoration (
color: Colors.red
),
child: new ListTile (
leading: const Icon(Icons.euro_symbol),
title: Text('250,00')
)
)
]
)
I was able to change the Background Color of ListTile by making it a child of Container Widget and adding color to the Container Widget.
Here drawerItem is the model class which holds the isSelected value. Color of background depends on isSelected value.
Note: For unselected items keep the color Transparent so you will still get the ripple effect.
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,
),
));
}
![](https://www.manongdao.com/static/images/pcload.jpg)