Search code examples
flutterdartflutter-futurebuilderflutter-sliver

Flutter FutureBuilder in SliverList


I want to list items from a FutureBuilder inside a SliverList. I found a possible solution here How to use FutureBuilder inside SliverList but not worked for me.

This is my code, it works, but i cannot declare the "childCount" as "snapshot.data.lenght" because of it is outside the FutureBuilder

return Scaffold(
  body: CustomScrollView(
    slivers: [
      SliverList(
        delegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            return FutureBuilder(
              future: getList1(),
              builder: (BuildContext context, snapshot) {
                if (snapshot.hasData) {
                  return Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: ListTile(
                      title: Text(
                        snapshot.data?[index]['docName'],
                      ),
                    ),
                  );
                } else {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }
              },
            );
          },
          childCount: 2,
        ),
      ),
    ],
  ),
);

Is there any better way or best practice to list FutureBluider in a SliverList?


Solution

  • Use FutureBuilder on top of SliverList and make sure to return sliver widget from futureBuilder on everystate.

    class _detailState extends State<detail> {
      late final future = getList1();
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: CustomScrollView(slivers: [
            FutureBuilder<List?>(
              future: future,
              builder: (BuildContext context, snapshot) {
                if (snapshot.hasData) {
                  return SliverList(
                      delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      return Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: ListTile(
                            title: Text(
                          "${snapshot.data?[index]['docName']}",
                        )),
                      );
                    },
                    childCount: snapshot.data?.length,
                  ));
                } else {
                  return const SliverToBoxAdapter(
                    child: Center(
                      child: CircularProgressIndicator(),
                    ),
                  );
                }
              },
            )
          ]),
        );
      }
    }