How to Implement Staggered GridView In Flutter?

· 4 min read
How to Implement Staggered GridView In Flutter
How to Implement Staggered GridView In Flutter

GridView Widget in Flutter is used to display the data in two-dimensional rows and columns. Users can choose any item by tapping on them.GridView Widget may contain Text Widget as an item or Image Widget as an item or it can be both as well depending on the user’s requirement. So In this article, We will discuss How to Implement Staggered GridView In Flutter?

What is Staggered GridView In Flutter?

Staggered GridView a grid layout where the cross axis is divided into multiple equally sized parts and places elements in optimal position based on available main axis space.

How to Implement Staggered GridView In Flutter?

Users can implement it using the below code snippet.

return new StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection(PRODUCTS_COLLECTION).snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return new Center(child: new CircularProgressIndicator());
        return new StaggeredGridView.count(
          physics: new BouncingScrollPhysics(),
          crossAxisCount: 2,
          children: buildGrid(snapshot.data.documents), 
          staggeredTiles: generateRandomTiles(snapshot.data.documents.length),
        );
      },
    );

List<Widget> buildGrid(List<DocumentSnapshot> documents) {
  List<Widget> _gridItems = [];
  _products.clear();

  for (DocumentSnapshot document in documents) {
    _products.add(Product.fromDocument(document));
  }

  for (Product product in _products) {
    _gridItems.add(buildGridItem(product));
  }

  return _gridItems;
}

Widget buildGridItem(Product product) {
  return new GestureDetector(
    child: new Card(
      elevation: 2.0,
      margin: const EdgeInsets.all(5.0),
      child: new Stack(
        alignment: Alignment.center,
        children: <Widget>[
          new Hero(
            tag: product.name,
            child: new Image.network(product.imageUrl, fit: BoxFit.cover),
          ),
          new Align(
            child: new Container(
              padding: const EdgeInsets.all(6.0),
              child: new Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  new Text('\u20B9 ${product.price}',
                      style: new TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 16.0)),
                  new Text(product.name,
                      style: new TextStyle(color: Colors.white)),
                ],
              ),
              color: Colors.black.withOpacity(0.4),
              width: double.infinity,
            ),
            alignment: Alignment.bottomCenter,
          ),
        ],
      ),
    ),
    onTap: () async {
      // TODO
    },
  );
}

List<StaggeredTile> generateRandomTiles(int count) {
  Random rnd = new Random();
  List<StaggeredTile> _staggeredTiles = [];
  for (int i=0; i<count; i++) {
    num mainAxisCellCount = 0;
    double temp = rnd.nextDouble();

    if (temp > 0.6) {
      mainAxisCellCount = temp + 0.5;
    } else if (temp < 0.3) {
      mainAxisCellCount = temp + 0.9;
    } else {
      mainAxisCellCount = temp + 0.7;
    }
    _staggeredTiles.add(new StaggeredTile.count(rnd.nextInt(1) + 1, mainAxisCellCount));
  }
  return _staggeredTiles;
}

Users can also Implement it using a plugin flutter_staggered_grid_view.

  • Go to pubspec.yaml file.
  • Add the following to your library and import a package below:
    import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

The code snippet will look like below:

StaggeredGridView.countBuilder(
  crossAxisCount: 4,
  itemCount: 8,
  itemBuilder: (BuildContext context, int index) => new Container(
      color: Colors.green,
      child: new Center(
        child: new CircleAvatar(
          backgroundColor: Colors.white,
          child: new Text('$index'),
        ),
      )),
  staggeredTileBuilder: (int index) =>
      new StaggeredTile.count(2, index.isEven ? 2 : 1),
  mainAxisSpacing: 4.0,
  crossAxisSpacing: 4.0,
)

Conclusion:

In this article, We have been through How to Implement Staggered GridView In Flutter?

Thanks for being with us on a Flutter Journey !!!

Keep Learning !!! Keep Fluttering !!!

Do let us know if you need any support for Flutter Development?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply