Nadeem Siddique
Nadeem Siddique

Reputation: 2128

How to resize Image according to parent element?

How do you guys keep an image size according to the height and width of parent element ? From my current code the I get image overflow error. I haven't specified any height/width for grid I was hoping for a way that it covers the entire grid space resizing itself.

Right now the Grid has automatically divided itself into columns and rows.

GridView.builder(
      controller: _scrollController,
      scrollDirection: Axis.vertical,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: snapitem.length,
      itemBuilder: (context, int index) {
        return InkWell(
          child: Card(
            child: Column(
              children: <Widget>[
                GridTile(
                  child: CachedNetworkImage(
                    imageUrl: snapitem[index].poster.toString(),
                    placeholder: Center(
                      child: CircularProgressIndicator(),
                    ),
                    errorWidget: Icon(Icons.broken_image),
                    fit: BoxFit.fill,
                  ),
                ),
                ButtonTheme.bar(
                  child: ListTile(
                    title: Text(
                      snapitem[index].title,
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
          splashColor: Colors.deepPurpleAccent,
        );
      },
    );

What I want to achieve is

I want the Grid a cards, within each card there is an image above and ListTile at the bottom

Upvotes: 0

Views: 1950

Answers (2)

scottstoll2017
scottstoll2017

Reputation: 1124

It's not MediaQuery(), that tells you the device screen size.

First question, if you aren't using a header or footer, why are you using a GridTile at all? From grid_tile.dart :

if (header == null && footer == null)
  return child;

So get rid of the GridTile unless you plan to add a header or footer. Next...

Since your CachedNetworkImage is now a direct child of the Column, you can wrap it in an Expanded. This will ignore any size information from the CachedNetworkImage and just fit it into the space available.

See https://docs.flutter.io/flutter/widgets/Expanded-class.html and Image Scale type center crop on flutter?

For more help with Flutter be sure to check out Flutter Community on Medium https://medium.com/flutter-community and our live help sessions every Wednesday at https://medium.com/flutter-community/flutterqanda/home

Upvotes: 1

mcfly
mcfly

Reputation: 834

Use mediaquery

if you want your image to be half the width of the device you can use this as :

width: Mediaquery.of(context).size.width / 2

Upvotes: 0

Related Questions