Magnus
Magnus

Reputation: 18758

Make CachedNetworkImage scale to fit height of ListTile

I want to place a CachedNetworkImage as the leading property inside a ListTile and have the image scale itself to fit the height of the ListTile. Is this possible without specifying a fixed height for the CachedNetworkImage?

What I have right now is this, which looks good but uses a fixed height of 32px.

return ListTile(
    title: Text(record.title),
    subtitle: Text(record.type),
    leading: CachedNetworkImage(imageUrl: url, fit: BoxFit.scaleDown, height: 32),
    onTap:_onListItemTap,
);

I'm not a fan of fixed dimensions, but perhaps I should be? Can I expect that 32px in Flutter will always be appropriate for a ListTile on any device?

Or is there a better way to make the size of my images adjust dynamically to the other content of the ListTile?

Upvotes: 2

Views: 4675

Answers (1)

rmtmckenzie
rmtmckenzie

Reputation: 40443

The leading element of a ListTile is normally expected to be an icon, although of course you can use anything else. But one way of doing it is to use IconTheme.of(context).size for your image's size, and then specify the size in your theme. That way, you could theoretically set theme based on the screen size at the top level of the app, and have it automatically propagate to wherever you use it. Most of the time you won't need to do that however, as flutter automatically handles different screen DPIs.

Another possible way of doing it would be to use an AspectRatio widget around the CachedNetworkImage, so that the width is dependent on the ListTile's height (which should be constant for a particular type of ListTile).

Upvotes: 1

Related Questions