vtisnado
vtisnado

Reputation: 500

Flutter SliverGrid population with API fetch

is there any working example of a SliverGrid populated with a fetch? All examples I found are with static/typed content.

What I want is to fill the SliverGrid with dynamic content pulled from API.

EDIT

This is the current structure I have, the SliverToBoxAdapter populates with a listView that scrolls horizontal, and below is the SliverGrid that I copied from and example an generate an infinite scroll with two columns.

I tried to add another SliverToBoxAdapter with a ListView vertical, but then the scroll stop working and need a height to be defined.

I want to know If I can populate SliverGrid in a same way than ListView and how to do that since I can't find any example.

I don't want to look lazy, but I'm new in Flutter and dont know how to accomplish this.

return Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
                //SOME OPTIONS AND VALUES HERE
            ),
            SliverToBoxAdapter(
              // this is populated with a fetch
              //child: NiceWidgetHere(), 
            ),
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: 1.5,
              ),
              delegate: SliverChildBuilderDelegate(
                 // Don't know what to do here
                //(context, index) => AnotherNiceWidgetHere(),
              ),
            )
          ],
        )
    );

In the image below you can see the layout I have. Both horizontal ListView and vertical GridView needs to fetch the content from json API, the fetch is not issue, since is already working in the horizontal ListView.

App Layout

Upvotes: 4

Views: 9949

Answers (1)

yla-dev
yla-dev

Reputation: 144

You have use the FutureBuilder as other's have stated. I did it by wrapping everything in SliverChildBuilderDelegate in a FutureBuilder. Here is my working copy.

Widget build(BuildContext context) {   
    APIServiceProvider  api = APIServiceProvider();
    Future<List<AttributeModel>> attributesListFuture = api.getAttributes();

    return SliverGrid(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4),
      delegate: SliverChildBuilderDelegate(
            (BuildContext context,int index)
            {
              return FutureBuilder(
                future: attributesListFuture ,
                builder: (context, snapshot)
                {

                      return snapshot.connectionState == ConnectionState.done? snapshot.hasData
                      ? HomeIconCell(snapshot.data[index])
                      :  Text('Retry')
                  : Text('progress');

                },
                ); 
            },
    ));
  }

Upvotes: 0

Related Questions