How to load dynamic data from REST API into Flutter SliverGrid widget

I need help with loading data from an API into a SliverGrid component. Most tutorials I see only show how to use SliverGrid with hardcoded data.

I want to fetch JSON data from a web service and display it in a grid layout. I already have this working for a horizontal ListView but can’t figure out how to do the same thing with SliverGrid.

Here’s my current setup:

return Scaffold(
  body: CustomScrollView(
    slivers: [
      SliverAppBar(
        // app bar configuration
      ),
      SliverToBoxAdapter(
        // this works fine with API data
        // child: MyHorizontalList(),
      ),
      SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 1.2,
        ),
        delegate: SliverChildBuilderDelegate(
          // how do I populate this with API response?
          // (context, index) => MyGridItem(),
        ),
      )
    ],
  )
);

I have a working API call that returns JSON data. The horizontal list above the grid loads this data perfectly. But I’m stuck on how to pass the fetched data to the SliverGrid delegate.

Can someone show me how to connect API data to SliverGrid? I’m still learning Flutter so a simple example would be really helpful.

You need proper state management here. Create a StatefulWidget and store your API response in a List variable. Call your API in initState() and use setState() to update the list when data comes back. In your SliverChildBuilderDelegate, set childCount to your list length and return grid items using the list data at each index. I ran into this exact problem last month - this approach works great. Don’t forget to handle the loading state. Show a loading indicator in the grid area while the API call runs. Way cleaner than wrapping everything in FutureBuilder with CustomScrollView.

Since your horizontal list API call already works, just reuse that approach. The trick is making sure your data’s ready when you build the SliverGrid. I’ve done this before - I stored the fetched data in a variable and rebuilt the widget once the API response came back. In your SliverChildBuilderDelegate, set childCount to match your data list length, then use the index to grab individual items from your API response. Try childCount: myApiData?.length ?? 0 and return MyGridItem(data: myApiData[index]) in the builder function. SliverGrid handles the grid layout automatically once you give it the right item count and data access pattern. Don’t forget to handle null cases while the API’s still loading.

wrap your SliverGrid in a FutureBuilder. load the API data in initState, then use snapshot.data for childCount in the builder. replace the hardcoded item count with data.length and access items with snapshot.data[index].