Search code examples
flutterdartgridviewflutter-layout

How to create GridView Layout in Flutter


I am trying to layout a 4x4 grid of tiles in flutter. I managed to do it with columns and rows. But now I found the GridView component. Could anyone provide an example on how to do it using it?

I can't really wrap my head around the docs. I don't seem to get the results I want.


Solution

  • A simple example loading images into the tiles.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp( MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
    
          color: Colors.white30,
          child: GridView.count(
              crossAxisCount: 4,
              childAspectRatio: 1.0,
              padding: const EdgeInsets.all(4.0),
              mainAxisSpacing: 4.0,
              crossAxisSpacing: 4.0,
              children: <String>[
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
                'http://www.for-example.org/img/main/forexamplelogo.png',
              ].map((String url) {
                return GridTile(
                    child: Image.network(url, fit: BoxFit.cover));
              }).toList()),
        );
      }
    }
    

    The Flutter Gallery app contains a real world example, which can be found here.

    enter image description here