16. Flutter Tutorial for Beginners – GridView Widget

0
495

In flutter we can easily create a grid view. To do that follow the code

GridView.count(
  // Create a grid with 2 columns.
  // crossAxixCount in the number of column
  crossAxisCount: 2,
  children: [
    Card(
        margin: EdgeInsets.all(8.0),
        child: Center(child: Text('ABC')),
    ),
    Card(
      margin: EdgeInsets.all(8.0),
      child: Center(child: Text('DEF')),
    ),
),

Example of crossAxisCount: 2 and crossAxisCount: 3

Full Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Container(
        child: GridView.count(
          // Create a grid with 2 columns. If you change the scrollDirection to
          // horizontal, this produces 2 rows.
          crossAxisCount: 2,
          children: [
            Card(
                margin: EdgeInsets.all(8.0),
                child: Center(child: Text('ABC')),
            ),
            Card(
              margin: EdgeInsets.all(8.0),
              child: Center(child: Text('DEF')),
            ),
            Card(
              margin: EdgeInsets.all(8.0),
              child: Center(child: Text('GHI')),
            ),
            Card(
              margin: EdgeInsets.all(8.0),
              child: Center(child: Text('JKL')),
            ),
            Card(
              margin: EdgeInsets.all(8.0),
              child: Center(child: Text('MNO')),
            ),
            Card(
              margin: EdgeInsets.all(8.0),
              child: Center(child: Text('PQR')),
            ),

          ],
        ),
      ),
    );
  }

}

LEAVE A REPLY

Please enter your comment!
Please enter your name here