简体   繁体   中英

Add dynamic list of Slivers returned by a function in CustomScrollView in flutter

I am trying to add a dynamic list of Sliverlist in CustomScrollView but it doesn't seem to work. The method correctly returns the list of slivers, which I verified by debugging. Here is the sample code of what I am trying to achieve

CustomScrollView(
          key: PageStorageKey<String>(myKey),
          slivers: _getSlivers(model.data, context),
        ),

Here is the _getSlivers metod:

List<Widget> _getSlivers(List myList, BuildContext context) 
{
  List<Widget> slivers = myList.map((key) => SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                   buildRow(index)
                  }
                },
                childCount: myList.length,
              ),
            ),
      ).toList();
    return slivers;
   }
 }

Your _getSlivers is not correct,

  • few errors with extra braces (could be typos)
  • you should return your buildRow
  • you should return SliverList

Not sure what your model.data or buildRow looks like but here is a quick example,

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  List<String> list = ['Title 1', 'Title 2', 'Title 3', 'Title 4', 'Title 5', 'Title 6', 'Title 7', 'Title 8', 'Title 9', 'Title 10', 'Title 11', 'Title 12', 'Title 13', 'Title 14', 'Title 15', 'Title 16', 'Title 17', 'Title 18', 'Title 19', 'Title 20'];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: CustomScrollView(
                //key: PageStorageKey<String>(myKey),
                slivers: <Widget>[
                  SliverAppBar(
                    title: Text('Test'),
                  ),
                  _getSlivers(list, context),
                ]
              ),
            ));
  }

  SliverList _getSlivers(List myList, BuildContext context) {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
          return buildRow(myList[index]);
        },
        childCount: myList.length,
      ),
    );
  }

  buildRow(String title) {
    return Padding(padding: const EdgeInsets.all(15.0),child: Text(title, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0)));
  }
}

演示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM