Flutter Change ListView to GridView on Button Click Dynamically

In Flutter GridView widget has a property named as crossAxisCount which is used to decide number of columns in a GridView in a single row. App developer can manage how much columns he wants to display in a single row. As we all know by default in ListView there is only one column in one row so using the State we can easily mange to update the crossAxisCount value. So in this tutorial we would Flutter Change ListView to GridView on Button Click Dynamically in Android iOS Example Tutorial.

Contents in this project Flutter Change ListView to GridView on Button Click Dynamically Android iOS Example Tutorial:

1. Import material.dart package in your app’s main.dart file.

2. Create void main runApp() method and here we would call our main MyApp class.

3. Create our main MyApp class extends with State less widget. In this class we would call our main sub-root child GridWidget class in body area.

4. Create a class named as GridWidget extends StatefulWidget. In this class we would make createState() method of State and pass GridViewState class along with it to enable State management in it.

5. Create our main child class named as GridViewState extends State. This is our main class in which we would make the GridView widget.

6. Create 3 num variable named as countValue, aspectWidth and aspectHeight.

  1. countValue : value is used as crossAxisCount value to manage how much columns developer wants to show in a single row.
  2. aspectWidth : Used in childAspectRatio property.
  3. aspectHeight : Used in childAspectRatio property.

7. Create a String type of List named as gridItems. Here we would pas 20 items and this all would be GridView items.

8. Create a function named as changeMode(). In this function we would Toggle the countValue, aspectWidth and aspectHeight values. Using this function we would make the GridView to ListView.

9. Create a function named as getGridViewSelectedItem(). In this function we would print the Selected GridView item on screen using Alert.

10. Create Widget Build area in GridViewState class. Now we would make a Column widget and put Expanded widget inside it. We would set the GridView.count() widget as Expanded widget child so they can expand on screen fully. Now we would make Raised Button.

11. Complete source code for main.dart file:

Screenshots:

Flutter Change ListView to GridView on Button Click Dynamically

Flutter Change ListView to GridView on Button Click Dynamically

Leave a Reply

Your email address will not be published. Required fields are marked *