GridView Flutter With Example

In this flutter tutorial, you can learn how to integrate gridview in flutter applications. Gridview is similar to listview but the difference is you can display items in gridview like two dimensional array.

GridView widget is used to display list items in grid. We can also dynamically add items in gridview flutter. So there is no requirement that list items are predetermined in gridview. GridView is implemented in flutter through various constructors: GridView, GridView.count(), GridView.builder(), GridView.custom(), GridView.extent().

 

GridView Flutter

GridView(
{Key key,
Axis scrollDirection: Axis.vertical,
bool reverse: false,
ScrollController controller,
bool primary,
ScrollPhysics physics,
bool shrinkWrap: false,
EdgeInsetsGeometry padding,
@required SliverGridDelegate gridDelegate,
bool addAutomaticKeepAlives: true,
bool addRepaintBoundaries: true,
bool addSemanticIndexes: true,
double cacheExtent,
List<Widget> children: const <Widget>[],
int semanticChildCount,
DragStartBehavior dragStartBehavior: DragStartBehavior.start,
Clip clipBehavior: Clip.hardEdge,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,
String restorationId}
)
 

children parameter is used to take array of widgets to display as list item in gridview widget. clipBehaviour parameter is used to decide whether GridView will be clipped or not. controller parameter is used to control the position of the scroll view. dragStartBehaviour property controls drag behaviour in GridView. gridDelegate is used to handle the layout of the children widget in the GridView.

 
 

GridView.builder

GridView.builder(
{Key key,
Axis scrollDirection: Axis.vertical,
bool reverse: false,
ScrollController controller,
bool primary,
ScrollPhysics physics,
bool shrinkWrap: false,
EdgeInsetsGeometry padding,
@required SliverGridDelegate gridDelegate,
@required IndexedWidgetBuilder itemBuilder,
int itemCount,
bool addAutomaticKeepAlives: true,
bool addRepaintBoundaries: true,
bool addSemanticIndexes: true,
double cacheExtent,
int semanticChildCount,
DragStartBehavior dragStartBehavior: DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,
String restorationId,
Clip clipBehavior: Clip.hardEdge}
)
 

scrollDirection parameter defines the direction in which list items are scrolling. By default scroll direction it is vertical. reverse parameter is used to simply reverse the order of widgets in gridview. physics parameter defines how gridview widget behaves when the user is doing scrolling in gridview and reaches end or start of gridview widget.

 
 

GridView.count

GridView.count(
{Key key,
Axis scrollDirection: Axis.vertical,
bool reverse: false,
ScrollController controller,
bool primary,
ScrollPhysics physics,
bool shrinkWrap: false,
EdgeInsetsGeometry padding,
@required int crossAxisCount,
double mainAxisSpacing: 0.0,
double crossAxisSpacing: 0.0,
double childAspectRatio: 1.0,
bool addAutomaticKeepAlives: true,
bool addRepaintBoundaries: true,
bool addSemanticIndexes: true,
double cacheExtent,
List<Widget> children: const <Widget>[],
int semanticChildCount,
DragStartBehavior dragStartBehavior: DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,
String restorationId,
Clip clipBehavior: Clip.hardEdge}
)
 

crossAxisCount parameter defines the number of columns used in GridView. crossAxisSpacing parameter is used to give space between each child listed along the cross axis. mainAxisSpacing parameter is used to give space between each child listed along the main axis. padding parameter is used to give space around the whole gridview widget.

shrinkWrap parameter is used to reduce extra space for scrolling list items. It takes only required space which children widgets allows. By default, the value of shrinkWrap parameter is false. Using these parameter we can prevent memory leak error in mobile applications.

 
 

GridView.custom

const GridView.custom(
{Key key,
Axis scrollDirection: Axis.vertical,
bool reverse: false,
ScrollController controller,
bool primary,
ScrollPhysics physics,
bool shrinkWrap: false,
EdgeInsetsGeometry padding,
@required SliverGridDelegate gridDelegate,
@required SliverChildDelegate childrenDelegate,
double cacheExtent,
int semanticChildCount,
DragStartBehavior dragStartBehavior: DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,
String restorationId,
Clip clipBehavior: Clip.hardEdge}
)
 
 

GridView.extent

GridView.extent(
{Key key,
Axis scrollDirection: Axis.vertical,
bool reverse: false,
ScrollController controller,
bool primary,
ScrollPhysics physics,
bool shrinkWrap: false,
EdgeInsetsGeometry padding,
@required double maxCrossAxisExtent,
double mainAxisSpacing: 0.0,
double crossAxisSpacing: 0.0,
double childAspectRatio: 1.0,
bool addAutomaticKeepAlives: true,
bool addRepaintBoundaries: true,
bool addSemanticIndexes: true,
double cacheExtent,
List<Widget> children: const <Widget>[],
int semanticChildCount,
DragStartBehavior dragStartBehavior: DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,
String restorationId,
Clip clipBehavior: Clip.hardEdge}
)
 
 

Final Code for GridView Flutter

 

my_gridview_constructors_page.dart

import ‘package:flutter/material.dart’;
import ‘country_info.dart’;

class MyGridViewConstructorsPage extends StatefulWidget {

MyGridViewConstructorsPage();

@override
_MyGridViewConstructorsPageState createState() => _MyGridViewConstructorsPageState();
}

class _MyGridViewConstructorsPageState extends State<MyGridViewConstructorsPage> {

CountryInfo usaInfo = CountryInfo(“USA”, “images/usa.jpg”);
CountryInfo englandInfo = CountryInfo(“England”, “images/england.jpg”);
CountryInfo franceInfo = CountryInfo(“France”, “images/france.jpg”);
CountryInfo russiaInfo = CountryInfo(“Russia”, “images/russia.jpg”);
CountryInfo canadaInfo = CountryInfo(“Canada”, “images/canada.jpg”);

List<CountryInfo> listCountries = [];

@override
Widget build(BuildContext context) {

listCountries = [];
listCountries.add(usaInfo);
listCountries.add(englandInfo);
listCountries.add(franceInfo);
listCountries.add(russiaInfo);
listCountries.add(canadaInfo);

return Scaffold(
appBar: AppBar(title: Text(‘GridView Constructors’)),
body: Container(
margin: EdgeInsets.only(top:15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
    width: double.infinity,
    height: 60,
    margin: EdgeInsets.symmetric(horizontal:30, vertical: 15),
    child: RaisedButton(
        color: Colors.pink,
        child: Text(‘GridView()’, style: TextStyle(color: Colors.white, fontSize: 25)),
        onPressed: () => Navigator.pushNamed(context, ‘/MyGridViewPage’, arguments: listCountries)),
),
Container(
    width: double.infinity,
    height: 60,
    margin: EdgeInsets.symmetric(horizontal:30, vertical: 15),
    child: RaisedButton(
        color: Colors.pink,
        child: Text(‘GridView.count()’, style: TextStyle(color: Colors.white, fontSize: 25)),
        onPressed: () => Navigator.pushNamed(context, ‘/MyGridViewCountPage’, arguments: listCountries)),
),
Container(
    width: double.infinity,
    height: 60,
    margin: EdgeInsets.symmetric(horizontal:30, vertical: 15),
    child: RaisedButton(
        color: Colors.pink,
        child: Text(‘GridView.builder()’, style: TextStyle(color: Colors.white, fontSize: 25)),
        onPressed: () => Navigator.pushNamed(context, ‘/MyGridViewBuilderPage’, arguments: listCountries)),
),
Container(
    width: double.infinity,
    height: 60,
    margin: EdgeInsets.symmetric(horizontal:30, vertical: 15),
    child: RaisedButton(
        color: Colors.pink,
        child: Text(‘GridView.custom()’, style: TextStyle(color: Colors.white, fontSize: 25)),
        onPressed: () => Navigator.pushNamed(context, ‘/MyGridViewCustomPage’, arguments: listCountries)),
),
Container(
    width: double.infinity,
    height: 60,
    margin: EdgeInsets.symmetric(horizontal:30, vertical: 15),
    child: RaisedButton(
        color: Colors.pink,
        child: Text(‘GridView.extent()’, style: TextStyle(color: Colors.white, fontSize: 25)),
        onPressed: () => Navigator.pushNamed(context, ‘/MyGridViewExtentPage’, arguments: listCountries)),
)],
),
),
);
}
}

 

my_gridview_page.dart

import ‘package:flutter/material.dart’;
import ‘package:fluttergridviewsample/my_card_layout.dart’;
import ‘country_info.dart’;

class MyGridViewPage extends StatefulWidget {

List<CountryInfo> listCountries;

MyGridViewPage({this.listCountries});

@override
_MyGridViewPageState createState() => _MyGridViewPageState();
}

class _MyGridViewPageState extends State<MyGridViewPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘GridView()’)),
body: Container(
color: Colors.white,
child: GridView(
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
    padding: const EdgeInsets.all(5.0),
    children: widget.listCountries.map((CountryInfo country) {
        return MyCardLayout(country);
    }).toList(),
)),
);
}
}

 

my_card_layout.dart

import ‘package:flutter/material.dart’;
import ‘package:fluttergridviewsample/country_info.dart’;

class MyCardLayout extends StatelessWidget {

CountryInfo countryInfo;

MyCardLayout(this.countryInfo);

@override
Widget build(BuildContext context) {
return Card(
clipBehavior: Clip.antiAliasWithSaveLayer,
shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(10.0),
),
child: Stack(fit: StackFit.expand, children: <Widget>[
Image.asset(countryInfo.imagePath, fit: BoxFit.cover),
Container(
    margin: EdgeInsets.only(left: 10, bottom: 10),
    alignment: Alignment.bottomLeft,
    child: Text(countryInfo.title, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25, color: Colors.white, shadows: [ Shadow( blurRadius: 3.0, color: Colors.black12, offset: Offset(3.0, 3.0), ), ], )),
)
]),
);
}
}

 

my_gridview_count_page.dart

import ‘package:flutter/material.dart’;

import ‘country_info.dart’;
import ‘my_card_layout.dart’;

class MyGridViewCountPage extends StatefulWidget {

List<CountryInfo> listCountries;

MyGridViewCountPage({this.listCountries});

@override
_MyGridViewCountPageState createState() => _MyGridViewCountPageState();
}

class _MyGridViewCountPageState extends State<MyGridViewCountPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘GridView.count()’)),
body: Container(
color: Colors.white,
child: GridView.count(
    crossAxisCount: 2,
    padding: const EdgeInsets.all(5.0),
    mainAxisSpacing: 5.0,
    crossAxisSpacing: 5.0,
    children: widget.listCountries.map((CountryInfo country) {
        return MyCardLayout(country);
    }).toList(),
))
);
}
}

 

my_gridview_builder_page.dart

import ‘package:flutter/material.dart’;

import ‘country_info.dart’;
import ‘my_card_layout.dart’;

class MyGridViewBuilderPage extends StatefulWidget {

List<CountryInfo> listCountries;

MyGridViewBuilderPage({this.listCountries});

@override
_MyGridViewBuilderPageState createState() => _MyGridViewBuilderPageState();
}

class _MyGridViewBuilderPageState extends State<MyGridViewBuilderPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘GridView.builder()’)),
body: Container(
color: Colors.white,
child: GridView.builder(
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
    itemBuilder: (BuildContext context, int index) {
        return MyCardLayout(widget.listCountries[index]);
    },
    itemCount: widget.listCountries.length,
    padding: const EdgeInsets.all(5.0),
)));
}
}

 

my_gridview_custom_page.dart

import ‘package:flutter/material.dart’;

import ‘country_info.dart’;
import ‘my_card_layout.dart’;

class MyGridViewCustomPage extends StatefulWidget {

List<CountryInfo> listCountries;

MyGridViewCustomPage({this.listCountries});

@override
_MyGridViewCustomPageState createState() => _MyGridViewCustomPageState();
}

class _MyGridViewCustomPageState extends State<MyGridViewCustomPage> {

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(title: Text(‘GridView.custom()’)),
body: Container(
color: Colors.white,
child: GridView.custom(
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
    childrenDelegate: SliverChildListDelegate(
    widget.listCountries.map((CountryInfo country) {
        return MyCardLayout(country);
    }).toList(),
    ),
    padding: const EdgeInsets.all(5.0),
)));
}
}

 

my_gridview_extent_page.dart

import ‘package:flutter/material.dart’;

import ‘country_info.dart’;
import ‘my_card_layout.dart’;

class MyGridViewExtentPage extends StatefulWidget {

List<CountryInfo> listCountries;

MyGridViewExtentPage({this.listCountries});

@override
_MyGridViewExtentPageState createState() => _MyGridViewExtentPageState();
}

class _MyGridViewExtentPageState extends State<MyGridViewExtentPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘GridView.extent()’)),
body: Container(
color: Colors.white,
child: GridView.extent(
    maxCrossAxisExtent: 300,
    children: widget.listCountries.map((CountryInfo country) {
        return MyCardLayout(country);
    }).toList(),
    padding: const EdgeInsets.all(5.0),
)));
}
}

 

main.dart

import ‘package:flutter/material.dart’;
import ‘package:fluttergridviewsample/my_gridview_count_page.dart’;
import ‘package:fluttergridviewsample/my_gridview_extent_page.dart’;
import ‘package:fluttergridviewsample/my_gridview_page.dart’;
import ‘package:fluttergridviewsample/my_gridview_constructors_page.dart’;

import ‘my_gridview_builder_page.dart’;
import ‘my_gridview_custom_page.dart’;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
    debugShowCheckedModeBanner: false,
    home: MyGridViewConstructorsPage(),
    onGenerateRoute: generateRoute,
);
}
}

Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;

switch (settings.name) {
case ‘/MyGridViewTypesPage’:
return MaterialPageRoute(builder: (_) => MyGridViewConstructorsPage());
case ‘/MyGridViewPage’:
return MaterialPageRoute(
    builder: (_) => MyGridViewPage( listCountries: args, ),
);
case ‘/MyGridViewCountPage’:
return MaterialPageRoute(
    builder: (_) => MyGridViewCountPage( listCountries: args, ),
);
case ‘/MyGridViewBuilderPage’:
return MaterialPageRoute(
    builder: (_) => MyGridViewBuilderPage( listCountries: args, ),
);
case ‘/MyGridViewCustomPage’:
return MaterialPageRoute(
    builder: (_) => MyGridViewCustomPage( listCountries: args, ),
);
case ‘/MyGridViewExtentPage’:
return MaterialPageRoute(
    builder: (_) => MyGridViewExtentPage( listCountries: args, ),
);
default:
return null;
}
}

 
 
 
gridview flutter
 

Leave a Reply