简体   繁体   中英

where is the index come from when using SliverChildBuilderDelegate of SliverList in flutter

Now I am using SliverList in flutter, in component I am using SliverList like this:

@override
  Widget buildResults(BuildContext context) {
    var channelRequest = new ChannelRequest();
    channelRequest.name = query;
    channelRequest.pageNum = 1;
    channelRequest.pageSize = 10;

    return FutureBuilder(
        future: ChannelAction.searchChannel(channelRequest),
        builder: (context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            List<Channel> post = snapshot.data;
            if (post != null) {
              return CustomScrollView(
                slivers: [
                  SliverList(delegate: SliverChildBuilderDelegate((context, index) {
                    return Slidable(
                      actionPane: SlidableScrollActionPane(),
                      child: Container(width: 0.0, height: 0.0),
                    );
                  }))
                ],
              );
            }
          }
          return Center(child: CircularProgressIndicator());
        });
  }

and now I do not know when is the index come from and how to pass the list into the SliverList , it seems the index is infinity. where is the index come from?

You can pass a childCount parameter to the SliverChildBuilderDelegate . The SliverChildBuilderDelegate will then call the function passed to it with the indexes 0 to childCount and you can use variables in your local scope or in your class to access the data.

Example:

class ExampleWidget extends StatelessWidget {
  const ExampleWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final data = ["a", "b", "c"];

    return CustomScrollView(
      slivers: [
        SliverList(
          delegate: SliverChildBuilderDelegate(
              (context, index) => Text("$index: ${data[index]}"),
              childCount: data.length), // <-- child count set here
        )
      ],
    );
  }
}

do not know when is the index come from and how to pass the list into the SliverList, it seems the index is infinity. where is the index come from?

Simply, you are right. If you DO NOT pass childCount of SliverChildBuilderDelegate , then you'll have infinite scrollable list. So the index is current item of the infinite items.

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