skip to Main Content

I have a list of containers which all have the same width and different heights. I want to fill the screen with them. From top left, to top right, to below, etc.

Similar thing can be seen in Pinterest and also Google Keep. Notice that the screen might resize so I don’t know the number of columns.

I have tried flutter_staggered_grid_view. The most similar thing I could find was the Masonry grid. But it changed the width of the containers.

2

Answers


  1. try adding this extension in your project:

    extension Responsive on BuildContext {
      T responsive<T>(
        T defaultVal, {
        T? sm,
        T? md,
        T? lg,
        T? xl,
      }) {
        final wd = MediaQuery.of(this).size.width;
        return wd >= 1280
            ? (xl ?? lg ?? md ?? sm ?? defaultVal)
            : wd >= 1024
                ? (lg ?? md ?? sm ?? defaultVal)
                : wd >= 768
                    ? (md ?? sm ?? defaultVal)
                    : wd >= 640
                        ? (sm ?? defaultVal)
                        : defaultVal;
      }
    }
    

    this extension will listen to changes of screen width and return a matched value, so your gridView would be something like this:

    GridView.count(
                crossAxisCount: context.responsive(2, sm: 2, md: 3, lg: 4, xl: 6),
                children: items
                    .map(
                      (final e) => Container(
                        padding: const EdgeInsets.all(10),
                        child: Text(e),
                      ),
                    )
                    .toList(),
              ),
    

    so gridView crossAxisCount will increase as long as the screen width goes larger.

    Login or Signup to reply.
  2. why don’t you use sliverGrid ?

    it will be something like this :

    class MySliverGrid extends StatelessWidget {
    
    
     final double width;
      final List<Widget> widgets;
      const MySliverGrid({Key? key, required this.width, required this.widgets})
          : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return SliverGrid(
            delegate: SliverChildListDelegate(widgets),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: MediaQuery.of(context).size.width ~/ width));
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search