在 CustomScrollView 中添加函数返回的 Slivers 动态列表

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

我正在尝试在 CustomScrollView 中添加 Sliverlist 的动态列表,但它似乎不起作用。该方法正确地 returns 条子列表,我通过调试验证了这一点。这是我想要实现的示例代码

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

这是 _getSlivers 方法:

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;
   }
 }

你的_getSlivers不正确,

  • 有一些额外大括号的错误(可能是拼写错误)
  • 你应该return你的buildRow
  • 你应该returnSliverList

不确定你的 model.databuildRow 是什么样子,但这里有一个简单的例子,

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)));
  }
}