Search code examples
flutterflutter-sliverstaggered-gridviewcustomscrollview

How to implement staggered grid view with SLIVERS in Flutter?


I want to implement a Staggered GridView, because my SliverGrid delegate requires an aspect ratio, and I want the grid items to be dynamically sized which is only possible with staggered gridview as far as I know.

My question is how can I implement a staggered gridview and use it in my CustomScrollView as a sliver?


Edit:

My pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  flutter_staggered_grid_view: ^0.5.1
  ...other packages

Solution

  • For Update version wrap GridView with SliverToBoxAdapter and set gridView physics to NeverScrollableScrollPhysics because CustomScrollView will handle scroll event.

    SliverToBoxAdapter(
      child: GridView.custom(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
    

    Test Widget

    Scaffold(
              body: CustomScrollView(
            slivers: [
              const SliverAppBar(
                title: Text("title"),
              ),
              SliverToBoxAdapter(
                child: GridView.custom(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: SliverQuiltedGridDelegate(
                    crossAxisCount: 4,
                    mainAxisSpacing: 4,
                    crossAxisSpacing: 4,
                    repeatPattern: QuiltedGridRepeatPattern.inverted,
                    pattern: const [
                      QuiltedGridTile(2, 2),
                      QuiltedGridTile(1, 1),
                      QuiltedGridTile(1, 1),
                      QuiltedGridTile(1, 2),
                    ],
                  ),
                  childrenDelegate: SliverChildBuilderDelegate(
                    (context, index) => Container(
                      color: Colors.cyanAccent,
                      child: Text("$index"),
                    ),
                    childCount: 44,
                  ),
                ),
              )
            ],
          )),
    

    flutter_staggered_grid_view: ^0.4.1 provides SliverStaggeredGrid to use as sliver's child.

     CustomScrollView(
       slivers: [
         SliverStaggeredGrid.countBuilder(...