How to have a ListView.builder (big list) in CustomScrollView in Flutter?

3k Views Asked by At

I'm trying to have a ListView builder with approximatively 500 items in a SliverList inside a CustomScrollView.

Scaffold(
    appBar: AppBar(
      title: Text(
        'Test',
        style: TextStyle(fontFamily: 'Diogenes', fontSize: 30),
      ),
      actions: [
        // IconButton(icon: Icon(Icons.list)),
      ],
    ),
    body: CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(...),
        SliverToBoxAdapter(...),
        SliverList(
            delegate: SliverChildBuilderDelegate((context, index) =>
                getHistoricalFixtures(pythiePerformance)))
      ],
    ),
  );

Widget getHistoricalFixtures(data) {
return Padding(
  padding: EdgeInsets.fromLTRB(10, 0, 10, 10),
  child: Container(
    height: 2000,
    child: _buildFixtures(data),
  ),
);

}

Widget _buildFixtures(data) {
return new ListView.builder(
    itemCount: data.historicalFixtures.length,
    physics: NeverScrollableScrollPhysics(),
    itemBuilder: (context, index) {
      return Container(...)
    });

}

It's working fine when the ListView is embedded within a Container with a fixed size. But, obviously, I can't see all items in the list.

I tried to put the ListView inside an Expanded widget but got this error:

Any help would be very appreciate.

Thanks.

2

There are 2 best solutions below

1
On

You have to use SliverList (about add list view inside CustomScrollView) or use SliverGrid (about add grid view inside CustomScrollView) like following codes:

SliverList(
          delegate: SliverChildListDelegate(
            [
              BodyWidget(Colors.blue),
              BodyWidget(Colors.red),
              BodyWidget(Colors.green),
              BodyWidget(Colors.orange),
              BodyWidget(Colors.blue),
              BodyWidget(Colors.red),
            ],
          ),
        ),

OR

SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          delegate: SliverChildListDelegate(
            [
              BodyWidget(Colors.blue),
              BodyWidget(Colors.green),
              BodyWidget(Colors.yellow),
              BodyWidget(Colors.orange),
              BodyWidget(Colors.blue),
              BodyWidget(Colors.red),
            ],
          ),
        ),

I hope this link will be useful :)

https://medium.com/codechai/flutter-listview-gridview-inside-scrollview-68b722ae89d4

0
On

I've used SliverToBoxAdapter instead of SliverList

                SliverToBoxAdapter(
                  child: Container(
                    height: 1000,
                    child: ListView.builder( ...