The GridView widget in Flutter provides a scrollable 2D array of widgets, allowing you to display a grid of items. It's a versatile and powerful widget commonly used for displaying lists of items in a grid format. In this section, we'll explore the attributes of the GridView widget and provide an example for your blog.
1. Attributes of GridView Widget:
1.1 children:
Description: A list of widgets to be displayed in the grid.
Example:
GridView( children: [ /* your widgets */, ], ),
1.2 gridDelegate:
Description: Defines the layout of the grid, such as the number of columns and their spacing.
Example:
GridView( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 16.0, mainAxisSpacing: 16.0, ), children: [ /* your widgets */, ], ),
1.3 scrollDirection:
Description: Specifies the scrolling direction of the grid, either horizontal or vertical.
Example:
GridView( scrollDirection: Axis.horizontal, children: [ /* your widgets */, ], ),
1.4 padding:
Description: Defines the padding around the entire grid.
Example:
GridView( padding: EdgeInsets.all(16.0), children: [ /* your widgets */, ], ),
2. Example of GridView Widget:
Let's create a simple Flutter application that uses the GridView widget to display a grid of images.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GridView Example'),
),
body: GridView(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 16.0,
mainAxisSpacing: 16.0,
),
padding: EdgeInsets.all(16.0),
children: [
//chnage path according to your images path
Image.network('https://example.com/image1.jpg'),
Image.network('https://example.com/image2.jpg'),
Image.network('https://example.com/image3.jpg'),
// Add more Image widgets as needed
],
),
),
);
}
}
In this example, we've created a Flutter app with a GridView containing a grid of images. The gridDelegate is set to have two columns with spacing between them, and the padding provides some space around the entire grid.