📜  flutter SliverList (1)

📅  最后修改于: 2023-12-03 15:15:07.757000             🧑  作者: Mango

Flutter SliverList

SliverList is a widget that helps to create a scrollable list of items. It works by lazily loading items as they are scrolled into view, which can make it more efficient than other list widgets.

How do I use SliverList?

To use SliverList, you need to wrap it in a CustomScrollView widget. This allows you to create a scrollable area that can contain multiple types of widgets.

Here's an example:

CustomScrollView(
  slivers: <Widget>[
    SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return ListTile(
            title: Text('Item $index'),
            onTap: () {
              // do something when the item is tapped
            },
          );
        },
        childCount: 50,
      ),
    ),
  ],
),

In this example, we're creating a CustomScrollView with a single SliverList. The SliverList is using a SliverChildBuilderDelegate to lazily create list items as they are scrolled into view. Each list item is a ListTile with a title and an onTap function.

What else can I do with SliverList?

SliverList provides several properties that allow you to customize the behavior and appearance of the list.

Reverse

The reverse property allows you to reverse the order of the list.

SliverList(
  delegate: SliverChildBuilderDelegate(
    // ...
  ),
  reverse: true,
),
Scroll Direction

The scrollDirection property allows you to change the direction that the list scrolls.

SliverList(
  delegate: SliverChildBuilderDelegate(
    // ...
  ),
  scrollDirection: Axis.horizontal,
),
Item Extent

The itemExtent property allows you to set a fixed height or width for each item in the list. This can improve performance by avoiding layout calculations for each item, but it can also make the list less flexible.

SliverList(
  delegate: SliverChildBuilderDelegate(
    // ...
  ),
  itemExtent: 50,
),
Padding

The padding property allows you to add padding around the list items.

SliverList(
  delegate: SliverChildBuilderDelegate(
    // ...
  ),
  padding: EdgeInsets.all(16),
),
Conclusion

SliverList is a powerful widget that makes it easy to create a scrollable list of items. With its lazy loading and customization options, it's a great choice for many types of list views in Flutter.