Search code examples
flutterflutter-layout

How to handle width of image inside the ListView in flutter?


My image is inside the ListView. And I want to give custom width to my image. But width property doesn't work for me. I am able to give custom height but the width property is not working.

Here is what image looks like:

Sample image

Here is the sample code:

Scaffold(
  appBar: AppBar(
    title: Text('Sample App'),
  ),
  body: ListView(
    children: <Widget>[
      Image.network(
        'https://assets.website-files.com/5e3c45dea042cf97f3689681/5e417cd336a72b06a86c73e7_Flutter-Tutorial-Header%402x.jpg',
      width: 100,
      height: 200,
      fit: BoxFit.fill,
      ),
    ],
  ),
);

Solution

  • By wrapping your Image widget inside Center widget, you can control the width and height of the image.

        Scaffold(
          appBar: AppBar(
            title: Text('Sample App'),
          ),
          body: ListView(
            children: <Widget>[
              Center(                // --> new change
                child: Image.network(
                  'https://assets.website-files.com/5e3c45dea042cf97f3689681/5e417cd336a72b06a86c73e7_Flutter-Tutorial-Header%402x.jpg',
                  width: 100,
                  height: 200,
                  fit: BoxFit.fill,
                ),
              ),
            ],
          ),
        );
    

    EDIT: If you would like to align your image other than the center, you can wrap it inside the Align widget.

        Scaffold(
          appBar: AppBar(
            title: Text('Sample App'),
          ),
          body: ListView(
            children: <Widget>[
              Align(
                alignment: Alignment.centerLeft,
                child: Image.network(
                  'https://assets.website-files.com/5e3c45dea042cf97f3689681/5e417cd336a72b06a86c73e7_Flutter-Tutorial-Header%402x.jpg',
                  width: 100,
                  height: 100,
                  fit: BoxFit.fill,
                ),
              ),
            ],
          ),
        );