在Flutter中添加由CustomScrollView中的函数返回的条的动态列表

时间:2019-12-13 18:11:24

标签: flutter flutter-sliver

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

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

1 个答案:

答案 0 :(得分:1)

您的_getSlivers不正确,

  • 一些带有大括号的错误(可能是拼写错误)
  • 您应该退还buildRow
  • 您应该返回SliverList

不确定您的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)));
  }
}

demo