Search code examples
flutterflutter-layout

GridLayout Item Overflow flutter


I have a gridlayout with griditems being basically : Cards with two things :

  • Image
  • Text

But the image is being loaded through the internet hence sometimes it overflows the grid item box and this box does not change the height, what i want is the image should be of fixed size.

Here is my code : (How do i do it ? )

import 'package:flutter/material.dart';
import '../models/dbModel.dart';

class GridLayout extends StatelessWidget {
  final List<DbModel> m;
  var appContext;

  GridLayout(this.m, this.appContext);

  Widget build(context) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, crossAxisSpacing: 7.0, mainAxisSpacing: 7.0),
      padding: const EdgeInsets.all(10.0),
      itemBuilder: (context, i) {
        return GridItem(appContext, m[i]);
      },
      itemCount: m.length,
    );
  }
}

class GridItem extends StatelessWidget {
  final appContext;
  final dbModel;

  GridItem(this.appContext, this.dbModel);

  Widget build(context) {
    return GestureDetector(
      onTap: () {},
      child: Card(
        child: Column(
          children: <Widget>[
            dbModel.img == "NOLINK" ? Image.network("https://i.ibb.co/Vv6cPj4/404.png",) : Image.network(dbModel.img),
            Container(
              padding: EdgeInsets.all(10.0),
              child: Text("${dbModel.title}"),
            ),
          ],
        ),
      ),
    );
  }
}

Solution

  • you need wrap image widget - Image.network with Expanded & add fit: BoxFit.cover,.

    working code:

    Widget build(context) {
        return GestureDetector(
          onTap: () {},
          child: Card(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch, //add this
              children: <Widget>[
                Expanded(
                  child: Image.network(
                    "https://i.ibb.co/Vv6cPj4/404.png",
                    fit: BoxFit.cover, // add this
                  ),
                ),
                Center(
                  child: Container(
                    padding: EdgeInsets.all(10.0),
                    child: Text("Title under"),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    

    output:

    enter image description here