Table of contents
1.
Introduction
2.
Flutter Sliver
2.1.
CustomScrollView
3.
Using Slivers in Flutter
4.
SliverAppBar
4.1.
Example
4.2.
Properties of SliverAppbar
5.
Sliver List
5.1.
Example
6.
SliverGrid
6.1.
Default Constructor
6.1.1.
Syntax
6.2.
Count Constructor
6.2.1.
Syntax
6.3.
Extent Constructor
6.3.1.
Syntax
6.4.
Example
7.
SliverPersistentHeader and SliverFixedExtentList
7.1.
Example
8.
Frequently Asked Questions
8.1.
What is a container class Flutter?
8.2.
What is a card in Flutter?
8.3.
What is CustomScrollView in flutter ?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Flutter Slivers

Author Rhythm Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A sliver is a part of a scrollable area that you may configure to behave differently. Slivers may be used to create bespoke scrolling effects such as elastic scrolling. Let’s learn how sliver works in flutter and how we can implement one. For better understanding, we have included some coding examples as well. Let’s dive right into it.

Flutter Sliver

A lower-level interface gives you complete freedom over how to construct a scrollable area. It comes in handy when scrolling through a significant number of child widgets in a scrollable area. Because they depend on the viewport, they can alter shape, size, and extent based on various events and offsets.

There are many kinds of slivers in a flutter, such as:

  • SliverAppBar
  • SliverList
  • SliverGrid
  • SliverPersistentHeader
  • SliverFixedExtentList
     

Before proceeding further, we need to know what a CustomScrollView is in Flutter.

CustomScrollView

Flutter's CustomScrollView is a scroll view that allows us to create various scrolling over effects, such as grids, lists, and extended headers. It features a sliver property that accepts a list of widgets like SliverAppBar, SliverFixedExtentList, SliverList, and SliverGrid, among others.

Using Slivers in Flutter

To implement Sliver, the entire content of the sliver’s segment must be placed inside a CustomScrollView regularly. Then we can condense the list of slivers to create the custom scrollable region.

Now, we need to understand each type of sliver.

SliverAppBar

SliverAppBar is a Flutter material design app bar that interfaces with a CustomScrollView. In general, it was the first child of CustomScrollView. It can change in height and float over the other scroll view widgets. It enables us to construct an app bar with different scrolling effects.

Let’s go through an example to have a better understanding.

Example

Let’s see how to use SilverAppBar with CustomScrollView

import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(actions: <Widget>[
              Icon(
                //Adding Person Icon
                Icons.person,
                size: 50,
              )
            ], title: Text("SliverAppBar"), backgroundColor: Colors.orange, expandedHeight: 80.0, floating: true, pinned: true)
            // Place sliver widgets here
          ],
        ),
      ),
    );
  }
}

Output:

Properties of SliverAppbar

The SliverAppBar's essential attributes are as follows:

Action: This property is used to generate widgets that appear to the right of the appBar title. In general, it is an an iconButton that depicts common operations.

Leading: This attribute is used to specify a widget to the left of the title. It is typically used to position the Menu Drawer widget.

backgroundColor: This parameter is used to specify the color of the sliver app bar's background.

Title: The title of the SliverAppBar is defined by this attribute. It works similarly to the AppBar title in that it displays the name of the program.

bottom: This property is used to add space to the bottom of the title where we may define any widget we want.

expandedHeight: The maximum height of the app bar that may be expanded when scrolling is specified by this parameter. It must be expressed as a double value.

flexibleSpace: This attribute is used to define a widget that is layered behind the toolbar and tab bar. Its height is the same as the total height of the app bar.

floating:When the user scrolls towards the app bar, this property defines whether or not the app bar will be shown.

Sliver List

SliverList is a sliver that stores the children in a one-dimensional or linear array. It is necessary to use a delegate parameter to deliver the items in the list so that they will scroll into view. The children's list can be specified with a SliverChildListDelegate or built with a SliverChildBuilderDelegate.

Let’s see an example of Sliver List.

Example

import 'package:flutter/material.dart';


void main() {
  runApp(const MyApp());
}


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


  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}


class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);


  @override
  _HomePageState createState() => _HomePageState();
}


class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: CustomScrollView(
      slivers: [
        const SliverAppBar(
          backgroundColor: Colors.orange,
          title: Text('Codingninjas.com'),
          expandedHeight: 30,
          collapsedHeight: 100,
        ),
        const SliverAppBar(
          backgroundColor: Colors.green,
          title: Text('SliverList Example'),
          floating: true,
        ),
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              return Card(
                margin: const EdgeInsets.all(15),
                child: Container(
                  color: Colors.blue[100 * (index % 9 + 1)],
                  height: 80,
                  alignment: Alignment.center,
                  child: Text(
                    "Item $index",
                    style: const TextStyle(fontSize: 30),
                  ),
                ),
              );
            },
            childCount: 5, // 1000 list items
          ),
        ),
      ],
    ));
  }
}


Output:

SliverGrid

SliverGrids arranges the children in a two-dimensional grid. It also employs a delegate or an explicit list to indicate the offspring, similar to the SliverList. However, it includes added formatting to the grid's cross-axis dimension. It allows you to set the grid layout in three ways:

Default Constructor

When a sliver grid displaying dynamic material retrieved from a database or an API is required.

Syntax

SliverGrid({
  Key? key, 
  required SliverChildDelegate delegate, 
  required SliverGridDelegate gridDelegate
})

Count Constructor

Use this if you require a sliver grid with a set amount of cells (tiles) in the cors axis.

Syntax

SliverGrid.count({
  Key? key, 
  required int crossAxisCount, 
  double mainAxisSpacing = 0.0, 
  double crossAxisSpacing = 0.0, 
  double childAspectRatio = 1.0, 
  List<Widget> children = const <Widget>[]
})

Extent Constructor

Use this constructor if you require a sliver grid with tiles that have a maximum cross-axis extension.

Syntax

SliverGrid.extent({
  Key? key, 
  required double maxCrossAxisExtent, 
  double mainAxisSpacing = 0.0, 
  double crossAxisSpacing = 0.0, 
  double childAspectRatio = 1.0, 
  List<Widget> children = const <Widget>[]
})

 

Example

Let’s discuss Slivergrid with an example.

import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Codingninjas.com'),
          elevation: 0,
        ),
        body: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(actions: <Widget>[
              Icon(
                Icons.person_add_alt_rounded,
                size: 40,
              )
            ], title: Text("SliverGrid"), leading: Icon(Icons.menu), backgroundColor: Colors.green, expandedHeight: 100.0, floating: true, pinned: true),
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
              ),
              delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                return new Container(color: _randomPaint(index), child: Text(index.toString()), height: 100.0);
              }),
            ),
          ],
        ),
      ),
    );
  }
}


Color _randomPaint(int index) {
  if (index % 3 == 0) {
    return Colors.yellowAccent;
  } else if (index % 3 == 1) {
    return Colors.orange;
  }
  return Colors.red;
}

 

Output:

SliverPersistentHeader and SliverFixedExtentList

A SliverFixedExtentList is a sliver that stores several children in a one-dimensional array or linear array with the same main-axis extent. It is more efficient than SliverList since no layouts on its children are required to derive the main-axis extent. It does not allow any separation between its children. Each kid must have the SliverConstraints. crossAxisExtent in the cross axis and itemExtent on the main axis

SliverPersistentHeader is a sliver that changes size as we scroll down.

Keeping the above statement in mind, the SliverPersistentHeader does not disappear when we scroll to the border of the viewport, which is opposed to the sliver's GrowthDirection. On the contrary, it changes size as we scroll.

Example

Let’s look at an example that utilises these two techniques to have a better understanding.
import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Codingninjas.com'),
          elevation: 0,
        ),
        body: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(actions: <Widget>[
              Icon(
                Icons.camera_front,
                size: 40,
              )
            ], title: Text("Sliver Example"), leading: Icon(Icons.menu), backgroundColor: Colors.green, expandedHeight: 100.0, floating: true, pinned: true),
            SliverFixedExtentList(
              itemExtent: 75,
              delegate: SliverChildListDelegate([
                Container(color: Colors.yellow),
                Container(color: Colors.orange),
                Container(color: Colors.red),
              ]),
            ),
            SliverToBoxAdapter(
              child: Container(
                color: Colors.pink,
                padding: const EdgeInsets.all(16.0),
                child: Text('Sliver Grid Header', style: TextStyle(fontSize: 28)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 

Output:

Frequently Asked Questions

What is a container class Flutter?

The Container class in Flutter is a useful widget that combines standard widget painting, positioning, and scaling. A Container class may be used to store and move one or more widgets on the screen as needed. A container is simply a box that is used to store stuff.

What is a card in Flutter?

A card is a piece of paper that is used to represent information related to each other, such as an album, a physical location, contact information, and so on. In Flutter, a card has rounded corners and is shadowed. It was mainly used to save the content and actions of a single item.

What is CustomScrollView in flutter ?

Flutter's CustomScrollView is a scroll view that allows us to create various scrolling over effects, such as grids, lists, and extended headers. It features a sliver property that accepts a list of widgets like as SliverAppBar, SliverFixedExtentList, SliverList, and SliverGrid, among others.

Conclusion

In this blog, we extensively discussed the Slivers in Flutter and learned different components and attributes of Flutter Slivers along with some programming examples.

We hope that our blog enhances your knowledge regarding the Flutter Sliver.

See Basics of C++ with Data StructureDBMSOperating System by Coding Ninjas, and keep practicing on our platform Coding Ninjas Studio.

To learn more about flutter, see the difference between Flutter and react nativerichtext widget in a FlutterFlutter interview questions, and the growing demand for Google’s Flutter.

If you think you are ready for the tech giants company, check out the mock test series on code studio.

You can also refer to our Guided Path on Coding Ninjas Studio to upskill yourself in domains like Data Structures and AlgorithmsCompetitive ProgrammingAptitude, and many more!. You can also prepare for tech giants companies like Amazon, Microsoft, Uber, etc., by looking for the questions asked by them in recent interviews. If you want to prepare for placements, refer to the interview bundle. If you are nervous about your interviews, you can see interview experiences to get the ideas about these companies' questions.

Nevertheless, you may consider our premium courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass