— Flutter, Widgets, Flutter Tips — 1 min read
This is just a short tip for something really simple. For some reason when you add a leading Widget to a ListTile in Flutter, an Icon for example, it doesn't seem to center vertically by default.
Here's a quick example of what I'm talking about:
And here's the code for the ListTile
widget displayed above:
1ListTile(2 tileColor: Colors.white,3 title: Text('Title text'),4 subtitle: Text('Subtitle text'),5 leading: Icon(Icons.ac_unit_outlined),6)
This feels really awkward and it sets off a mild case of OCD for me. Anyway, you can fix this by wrapping the icon in a Container
widget and giving it infinity for its height:
1ListTile(2 tileColor: Colors.white,3 title: Text('Title text'),4 subtitle: Text('Subtitle text'),5 leading: Container(6 height: double.infinity,7 child: Icon(Icons.ac_unit_outlined),8 ),9)
And here's what the result looks like:
By the way if you're using flutter_lints
you might get a linting error about using Container as whitespace. I'm personally fine with ignoring this because Container obviously has utility in the above case, but if you want to quash it just use:
1// ignore: sized_box_for_whitespace
Another thing I don't like is how far away the icon is from the title and subtitle. You can tweak this with ListTile's minLeadingWidth
property. Here's an example:
1ListTile(2 tileColor: Colors.white,3 title: Text('Title text'),4 subtitle: Text('Subtitle text'),5 minLeadingWidth: 0,6 // ignore: sized_box_for_whitespace7 leading: Container(8 height: double.infinity,9 child: Icon(Icons.ac_unit_outlined),10 ),11)
And here's what this looks like: