Reputation: 368
I am building a wallpaper app and want to implement a feature of switching views, like switching from GridView
to ListView
on the press of an IconButton
in FLutter
would look something like this:
The only way I could think of implementing this feature is by changing the crossAxisCount
value in the GridView.count()
method by hooking up a counter to the crossAxisCount
property and controlling it through a function on click of an IconButton
, this works but I have to Hot Reload my application every time the counter is incremented or decremented,
Any Suggestions or fix to this problem is welcomed.
Upvotes: 1
Views: 3867
Reputation: 6164
You can simply use ternary operators and setState()
to achieve what you want.
First, declare a boolean above your widget build
. Then you can use ternary operators to change it from gridview to listview.
bool isGridView=true;
@override
Widget build(BuildContext context) {
Scaffold(
body: isGridView ? GridView.builder():ListView.builder(),
);
}
In your onPressed(), you can call setState()
:
setState(() {
isGridView=false;
});
Upvotes: 7