Search code examples
flutterdartlayout

Why isn't my image filling the space with BoxFit.fill in Flutter?


I am trying to make an image in a Row widget (second ListView item) fill the entire available space, but it is not working as expected. I’ve set the BoxFit.fill property, but the image does not stretch to fill the container completely, unlike the Container in the ContainerCard widget (first ListView item), which fills the available space as intended.

Here’s the relevant code:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('TestApp'),),
      body: ListView(
        padding: EdgeInsets.all(15),
        children: [         
          ContainerCard(),
          ImageCard()
        ],
      ),
    );
  }
}

class ContainerCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Card(
      child: IntrinsicHeight(
        child: Row(
          children: [
            Container(color: Colors.red, width: 100),
            Expanded(
              child: Container(color: Colors.amber, height: 200,)
            ),
          ],
        ),
      ),
    );
  }
}

class ImageCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Card(
      child: IntrinsicHeight(
        child: Row(
          children: [
            Image.network(
              'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg',
              width: 100,
              fit: BoxFit.fill,
            ),
            Expanded(
              child: Container(color: Colors.amber, height: 200)
            ),
          ],
        ),
      ),
    );
  }
}

I expected the image to stretch and fill the entire available width, just like the Container in ContainerCard, even if it distorts the aspect ratio.


Solution

  • You need to stretch the items, crossAxisAlignment: CrossAxisAlignment.stretch

    class ImageCard extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Card(
          child: IntrinsicHeight(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Image.network(
                  'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg',
                  width: 100,
                  fit: BoxFit.fill,
                ),
                Expanded(child: Container(color: Colors.amber, height: 200)),
              ],
            ),
          ),
        );
      }
    }