How to Create Dynamic Gridview in Flutter?

In this blog post, we’ll explore the capabilities of Dynamic Gridview in Flutter, enabling you to build flexible and responsive grid-based interfaces. Follow along with a real-world code example to master the art of implementing a dynamic GridView in Flutter.

Dynamic GridView in Flutter

A GridView in Flutter is a scrollable, 2D array of widgets that’s perfect for displaying data in a grid format. When the content of the grid needs to change dynamically, Flutter’s GridView.builder comes into play.

This dynamic approach is invaluable when working with data sets that can grow or shrink during runtime, offering a seamless user experience.

Dynamic Gridview in Flutter

Let’s delve into a real-world example to illustrate the implementation of a dynamic GridView in Flutter.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DynamicGridViewExample(),
    );
  }
}

class DynamicGridViewExample extends StatefulWidget {
  @override
  _DynamicGridViewExampleState createState() => _DynamicGridViewExampleState();
}

class _DynamicGridViewExampleState extends State<DynamicGridViewExample> {
  List<String> data = [
    'Item 1',
    'Item 2',
    'Item 3',
    'Item 4',
    'Item 5',
    'Item 6',
    'Item 7',
    'Item 8',
    'Item 9',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dynamic GridView Example'),
      ),
      body: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, // Set the number of columns
          crossAxisSpacing: 8.0, // Set the spacing between columns
          mainAxisSpacing: 8.0, // Set the spacing between rows
        ),
        itemCount: data.length,
        itemBuilder: (context, index) {
          return Card(
            child: Center(
              child: Text(data[index]),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Add a new item to the list
          setState(() {
            data.add('New Item');
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

What code want to say:

  1. We create a Flutter project and a StatefulWidget named DynamicGridViewExample.
  2. In the state class (_DynamicGridViewExampleState), we initialize a List of Strings named data with some sample items.
  3. The build method returns a Scaffold widget containing an AppBar, a dynamic GridView, and a FloatingActionButton.
  4. The dynamic GridView is created using the GridView.builder constructor, allowing for the efficient creation of grid items based on the length of the data.
  5. The gridDelegate property is used to configure the layout of the grid, specifying the number of columns (crossAxisCount) and the spacing between them.
  6. The itemBuilder the function is responsible for creating each grid item. It takes an index and returns a widget to be displayed at that index in the grid.
  7. The FloatingActionButton is used to demonstrate the dynamic nature of the GridView. When pressed, it adds a new item (‘New Item’) to the list, triggering a rebuild of the UI with the updated data.

Output:

Output of Dynamic GridView in Flutter

Another Way Dynamic Gridview in Flutter

If you prefer using GridView.count for a fixed number of columns, here’s the modified example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DynamicExpansionGridExample(),
    );
  }
}

class DynamicExpansionGridExample extends StatefulWidget {
  @override
  _DynamicExpansionGridExampleState createState() => _DynamicExpansionGridExampleState();
}

class _DynamicExpansionGridExampleState extends State<DynamicExpansionGridExample> {
  List<String> data = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dynamic ExpansionGrid Example'),
      ),
      body: GridView.count(
        crossAxisCount: 2,
        crossAxisSpacing: 8.0,
        mainAxisSpacing: 8.0,
        children: List.generate(data.length, (index) {
          return ExpansionTile(
            title: Text(data[index]),
            children: [
              // Additional content for each item goes here
              ListTile(
                title: Text('Additional Content 1'),
              ),
              ListTile(
                title: Text('Additional Content 2'),
              ),
            ],
          );
        }),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Add a new item to the list
          setState(() {
            data.add('New Item');
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

What code want to say

This modified example achieves the same dynamic grid layout using GridView.count a fixed number of columns, maintaining the expandable nature of each item.

Output:

Screenshot 2024 03 04 at 14.20.50

Also Read:

Conclusion

Mastering the dynamic GridView in Flutter opens up exciting possibilities for building interactive and visually appealing grid-based layouts.

The provided code example showcases the flexibility and ease of implementing a dynamic GridView, allowing you to confidently integrate this powerful widget into your Flutter projects.

Experiment with the code, customize the grid layouts and enhance your app’s user interface with dynamic and responsive grid views.

Share:
Ambika Dulal

Ambika Dulal is a Flutter Developer from Nepal who is passionate about building beautiful and user-friendly apps. She is always looking for new challenges and is eager to learn new things. She is also a strong believer in giving back to the community and is always willing to help others.

Leave a Comment

AO Logo

App Override is a leading mobile app development company based in Kathmandu, Nepal. Specializing in both Android and iOS app development, the company has established a strong reputation for delivering high-quality and innovative mobile solutions to clients across a range of industries.

Services

UI/UX Design

Custom App Development

Mobile Strategy Consulting

App Testing and Quality Assurance

App Maintenance and Support

App Marketing and Promotion

Contact

App Override

New Plaza, Kathmandu