Grid in Flutter
In Flutter, the `GridView` widget allows you to create a 2D array of widgets, or a grid. It is useful when you want to display a large number of items in a grid layout. There are several ways to create a grid in Flutter, including using `GridView.count`, `GridView.extent`, and `GridView.builder`.
### 1. GridView.count
The `GridView.count` constructor is ideal when you know the number of columns you want.
```dart
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.count Example'),
),
body: GridView.count(
// Number of columns in the grid
crossAxisCount: 2,
// Space between the items in the grid
crossAxisSpacing: 10,
mainAxisSpacing: 10,
// Padding around the grid
padding: EdgeInsets.all(10),
// The list of items to display in the grid
children: List.generate(20, (index) {
return Container(
alignment: Alignment.center,
color: Colors.blue[100 * (index % 9 + 1)],
child: Text(
'Item $index',
style: TextStyle(fontSize: 16),
),
);
}),
),
),
);
}
}
```
### 2. GridView.extent
The `GridView.extent` constructor allows you to specify the maximum width of each item. The number of columns is automatically determined based on the available width.
```dart
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.extent Example'),
),
body: GridView.extent(
// Maximum width of each item
maxCrossAxisExtent: 100,
// Space between the items in the grid
crossAxisSpacing: 10,
mainAxisSpacing: 10,
// Padding around the grid
padding: EdgeInsets.all(10),
// The list of items to display in the grid
children: List.generate(20, (index) {
return Container(
alignment: Alignment.center,
color: Colors.green[100 * (index % 9 + 1)],
child: Text(
'Item $index',
style: TextStyle(fontSize: 16),
),
);
}),
),
),
);
}
}
```
### 3. GridView.builder
The `GridView.builder` constructor is the most flexible, as it allows for dynamically generating grid items based on a builder function. This is useful for large or infinite grids.
```dart
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.builder Example'),
),
body: GridView.builder(
// Delegate to build the grid
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // Number of columns
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
// Number of items in the grid
itemCount: 50,
// Padding around the grid
padding: EdgeInsets.all(10),
// Item builder function
itemBuilder: (context, index) {
return Container(
alignment: Alignment.center,
color: Colors.red[100 * (index % 9 + 1)],
child: Text(
'Item $index',
style: TextStyle(fontSize: 16),
),
);
},
),
),
);
}
}
```
### Explanation of Key Properties:
- **crossAxisCount**: Defines the number of columns in the grid.
- **maxCrossAxisExtent**: Defines the maximum width of each item in the grid.
- **crossAxisSpacing**: The space between items along the cross axis.
- **mainAxisSpacing**: The space between items along the main axis.
- **padding**: Adds padding around the grid.
- **itemCount**: Number of items in the grid (used in `GridView.builder`).
- **itemBuilder**: Function to build each item in the grid (used in `GridView.builder`).
These examples demonstrate how to use the `GridView` widget in Flutter to create different types of grid layouts based on your needs.
Sure, here are five examples of how you can use `GridView` in different contexts within a Flutter application:
### Example 1: Photo Gallery Grid
A common use case for a grid layout is a photo gallery.
```dart
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('Photo Gallery'),
),
body: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // 3 columns
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: 30, // Total number of photos
itemBuilder: (context, index) {
return Image.network(
'https://picsum.photos/id/${index + 1}/200/200',
fit: BoxFit.cover,
);
},
),
),
);
}
}
```
### Example 2: Product Grid for E-commerce
Displaying products in a grid layout in an e-commerce app.
```dart
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('Product Grid'),
),
body: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
padding: EdgeInsets.all(10),
children: List.generate(10, (index) {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Image.network(
'https://picsum.photos/200/300?random=$index',
fit: BoxFit.cover,
width: double.infinity,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Product $index'),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Text('\$${index * 10 + 0.99}'),
),
],
),
);
}),
),
),
);
}
}
```
### Example 3: Icon Grid for a Settings Page
An icon grid for navigating various settings options.
```dart
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('Settings'),
),
body: GridView.extent(
maxCrossAxisExtent: 150,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
padding: EdgeInsets.all(10),
children: List.generate(8, (index) {
return Card(
child: InkWell(
onTap: () {
// Handle onTap
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.settings,
size: 50,
color: Colors.blue,
),
SizedBox(height: 10),
Text('Setting $index'),
],
),
),
);
}),
),
),
);
}
}
```
### Example 4: Dashboard with Various Widgets
A dashboard with different widgets arranged in a grid layout.
```dart
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('Dashboard'),
),
body: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
padding: EdgeInsets.all(10),
children: [
Card(
child: Center(child: Text('Widget 1')),
),
Card(
child: Center(child: Text('Widget 2')),
),
Card(
child: Center(child: Text('Widget 3')),
),
Card(
child: Center(child: Text('Widget 4')),
),
],
),
),
);
}
}
```
### Example 5: Infinite Scroll Grid
A grid that fetches more items as you scroll down, useful for endless scrolling.
```dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: InfiniteGridScreen(),
);
}
}
class InfiniteGridScreen extends StatefulWidget {
@override
_InfiniteGridScreenState createState() => _InfiniteGridScreenState();
}
class _InfiniteGridScreenState extends State<InfiniteGridScreen> {
List<int> _items = List.generate(20, (index) => index);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Infinite Scroll Grid'),
),
body: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification scrollInfo) {
if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) {
_loadMore();
}
return false;
},
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: _items.length,
itemBuilder: (context, index) {
return Container(
alignment: Alignment.center,
color: Colors.amber[100 * (index % 9 + 1)],
child: Text(
'Item ${_items[index]}',
style: TextStyle(fontSize: 16),
),
);
},
),
),
);
}
void _loadMore() {
setState(() {
_items.addAll(List.generate(20, (index) => _items.length + index));
});
}
}
```
These examples cover a range of common use cases for grid layouts in Flutter applications, showcasing the flexibility and power of the `GridView` widget.
0 Comments