flutter
  1. flutter-slivers

Flutter Slivers

Flutter slivers are a powerful and flexible widget that enables developers to create custom, scrollable interfaces with varying layers or sections. Slivers are essentially a scrolling element that allows complex UIs to be navigated and scrolled through.

Syntax

Slivers can be implemented as SliverAppBar, SliverList, SliverGrid, SliverToBoxAdapter, etc.

CustomScrollView(
  slivers: <Widget>[
    SliverAppBar(
      // Properties to configure the SliverAppBar
      backgroundColor: Colors.red,
      pinned: true,
      // ...
    ),
    SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          // Create the item widgets here
        },
      ),
    ),
  ],
)

Example

Here’s an example of implementing a SliverAppBar along with a SliverList:

CustomScrollView(
  slivers: <Widget>[
    SliverAppBar(
      expandedHeight: 200.0,
      flexibleSpace: const FlexibleSpaceBar(
        title: Text('Flutter Slivers'),
        background: Image(
          image: AssetImage('assets/images/flutter-slivers.jpg'),
          fit: BoxFit.cover,
        ),
      ),
    ),
    SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return ListTile(
            title: Text('Item $index'),
          );
        },
      ),
    ),
  ],
);

Output

The above code will create a screen with a SliverAppBar that can be scrolled to reveal more items in the SliverList. When scrolled, the image in the SliverAppBar will shrink and collapse to reveal the title of the app and the list below.

Explanation

In the given example, a CustomScrollView widget has been implemented with a SliverAppBar and SliverList. The SliverAppBar consists of an expandedHeight and a flexibleSpace widget. The SliverList displays a list of items in the scrolling area and takes a delegate with a SliverChildBuilderDelegate to build each item widget.

Use

Flutter slivers can be used to create complex scrollable interface elements, such as:

  • Parallax scrolling effects
  • Collapsible headers
  • Nested scrolling sections
  • Complex list views

Important Points

  • The CustomScrollView widget is used to combine different types of Sliver widgets.
  • A SliverAppBar widget is commonly used to create a collapsible app bar.
  • A SliverList is used to display a list of items in a scrolling area.

Summary

Flutter slivers are an incredibly versatile and powerful feature, allowing developers to create scrolling interfaces with a wide range of unique customizations and effects. With slivers, complex scrollable elements can be built with ease and efficiency, contributing to an engaging, user-friendly interface experience.

Published on: