Flutter GridView Builder comes handy when you have a lot of data to show and you want to be fast displaying them.
ListView draws everything at time in column or row.
ListView.builder draws in column or row on demand and save memory.
GridView.builder draws in column or row on demand and save memory.
In general ListView would draw everything at a time. If you a lot of info to display, then they will all get drawn at one time.
But if you use GridView.builder, then Flutter would draw them only when you need them.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
HomeScreen({Key? key}) : super(key: key);
final List<Map> myProducts =
List.generate(100000, (index) => {"id": index, "name": "Product $index"})
.toList();
@override
Widget build(BuildContext context) {
print(MediaQuery.of(context).size.width);
return Scaffold(
appBar: AppBar(
title: const Text('GridView'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
// implement GridView.builder
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 180,
childAspectRatio:1,
crossAxisSpacing: 20,
mainAxisSpacing: 20),
itemCount: myProducts.length,
itemBuilder: (BuildContext ctx, index) {
return Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(15)),
child: Text(
myProducts[index]["name"],
style: TextStyle(color: Colors.white, fontSize: 20),
),
);
}),
),
);
}
}
maxCrossAxisExtent tells you what could be maximum width of your cross axis element. Like the maximum width of each of the grid. But when it draws, it could be less than that.
SliverGridDelegateWithMaxCrossAxisExtent()
You need to tell cross axis alignment settings to flutter. The above widget takes the settings properties.
Gridview builder saves battery and makes the ui more responsive.
Both GridView.builder and ListView.builder are the same thing in terms of memory efficiency and performance. They both create items as they’re scrolled onto the screen. The only difference is that one creates grid and the other one creates list.
Both Gridview.builder and ListView.builder use lazy rendering method, that also means they use virtual memory.