GridView.extent
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: Text('Grid'),
),
body: Container(
child: GridView.extent(
maxCrossAxisExtent: width / 3,
children: List.generate(
20,
(index) => Container(
color: Colors.amber,
margin: const EdgeInsets.all(5),
alignment: Alignment.center,
child: Text('Widget : $index'),
),
),
),
),
);
}
In GridView.extent
, we use maxCrossAxisExtent
to set the maximum space we want to give to each children
. Here we are giving a maxCrossAxisExtent: width / 3
, that means we are giving each children 1/3 of the width available.
GridView.custom
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Grid'),
),
body: Container(
child: GridView.custom(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
childrenDelegate: SliverChildBuilderDelegate(
(context, index) {
return Container(
color: Colors.amber,
margin: const EdgeInsets.all(5),
alignment: Alignment.center,
child: Text('Widget $index'),
);
},
childCount: 200,
),
),
),
);
}
In GridView.custom
, we get option to use SliverGridDelegate gridDelegate and SliverChildDelegate childrenDelegate
.
For SliverGridDelegate
you can use :
- SliverGridDelegateWithFixedCrossAxisCount - No. of children in the cross axis
- SliverGridDelegateWithMaxCrossAxisExtent - Max cross axis space for each children (Same that we re doing using
GridView.extent
)
For SliverChildDelegate
you can use :
- SliverChildBuilderDelegate - Provides builder callback to construct the children
- SliverChildListDelegate - Provides option to make explicit list of children.
Both of the above code generates the same output.Grid.extent
is just a shorthand to create grid layout with fixed children size while we can do the same thing using GridView.custom
as it is more flexible and you can do more things using it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…