Dolphin
Dolphin

Reputation: 38985

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?

Upvotes: 1

Views: 859

Answers (2)

blackkara
blackkara

Reputation: 5052

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.

Upvotes: 2

Tobias Braun
Tobias Braun

Reputation: 315

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

Upvotes: 1

Related Questions