What I’m trying to do is have a GridView with a variable/dynamic CrossAxisCount.
I have a FutureBuilder retrieving data from an API and sometimes I need to show one item per line and sometimes I need to show two items per line, depending on some item properties.
Being more specific the condition is:
if (previousItem != null && items[index].idCategory != previousItem.idCategory && items[index].isOdd)
.
The list of items would have around 700 items, please remember that crossAxisCount is final in most of the constructors.
I found the following code on Stackoverflow but it is not compatible with the latest version of flutter_staggered_grid_view.
I have other things on the app using version 0.6.2 of that package so I cannot use version ^0.4.0.
class Staggered extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: StaggeredGridView.count(
crossAxisCount: 2,
mainAxisSpacing: 5,
crossAxisSpacing: 5,
children: List.generate(14, (index){
return Container(
child: Center(
child: Text("${index+1}"),
),
color: Colors.blue,
);
}),
staggeredTiles: buildTiles(),
),
),
);
}
List<StaggeredTile> buildTiles(){
return List.generate(14, (index){
if((index+1)%7 == 0){
return StaggeredTile.count(2, 1);
}else{
return StaggeredTile.count(1, 1);
}
});
}
}
2
Answers
So, you want a custom
GridView
widget which showscrossAxisCount
dynamically based on your API response. Sometimes, single or N items in a row. So, here I wrote a sample code for you. I hope it helps you. Feel free to ask.Preview:
![Preview](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
It seems like there is a slight API change that has renamed
StaggeredGridView.count()
intoStaggeredGrid.count()
.Simply omitting "View" should suffice.