Search code examples
dartflutterflutter-sliversliver-grid

How to use itemCount in SliverGrid?


Most probably I got the concept my SliverGrid entirely wrong,

What I am trying to do is, UI wise I want the collapsible SliverAppBar which is already available in Flutter. My main content body is set of images coming from API response and already parsed and loaded to a List variable.

Now here is my code:

body: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(expandedHeight: 150.0, backgroundColor: Colors.green),
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3
              ),
              delegate: SliverChildBuilderDelegate((BuildContext context, int index){
                return Padding(
                  padding: EdgeInsets.symmetric(horizontal: 2.0, vertical: 2.0),
                  child: InkWell(
                    child: Card(
                      elevation: 8.0,
                      child: FadeInImage.memoryNetwork(fit: BoxFit.cover,image: myimagelist[index].thumbnail, placeholder:kTransparentImage,fadeInCurve: Curves.bounceIn,),
                    ),
                  )
                );
              }),
            ),
          ],
        ),

I think this is probably because I can't tell the widget that how long is my data. For GridView.builder itemCount parameter is there, but SliverGrid doesn't have such an option. What do here?


Solution

  • SliverGrid widget doesn't have a property named itemCount. However, if you read the docs, you'll see that it's delegate property which takes a SliverChildBuilderDelegate has a property called childCount. You can use this property to set the number of childrens you want in your slivergrid.

    delegate: SliverChildBuilderDelegate((BuildContext context, int index){
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 2.0, vertical: 2.0),
        child: InkWell(
          child: Card(
            elevation: 8.0,
            child: FadeInImage.memoryNetwork(fit: BoxFit.cover,image: myimagelist[index].thumbnail, placeholder:kTransparentImage,fadeInCurve: Curves.bounceIn,),
             ),
          )
        );
      },
      childCount: 3, // Your desired amount of children here 
    ),