How to use SliverAppBar in flutter

The SliverAppBar is a powerful widget in Flutter that allows us to create collapsible and flexible app bars that can adjust based on scrolling behaviors. It's commonly used with the SliverList, SliverGrid, or CustomScrollView to create custom scrolling effects. This Answer will cover using SliverAppBar in Flutter with code examples.

Constructor and parameters

The SliverAppBar widget provides a constructor with various parameters to customize its behavior and layout.

const SliverAppBar({
  Key? key,
  Widget? leading,
  bool automaticallyImplyLeading = true,
  Widget? title,
  List<Widget>? actions,
  Widget? flexibleSpace,
  PreferredSizeWidget? bottom,
  double? elevation,
  double? scrolledUnderElevation,
  Color? shadowColor,
  Color? surfaceTintColor,
  bool forceElevated = false,
  Color? backgroundColor,
  Color? foregroundColor,
  IconThemeData? iconTheme,
  IconThemeData? actionsIconTheme,
  bool primary = true,
  bool? centerTitle,
  bool excludeHeaderSemantics = false,
  double? titleSpacing,
  double? collapsedHeight,
  double? expandedHeight,
  bool floating = false,
  bool pinned = false,
  bool snap = false,
  bool stretch = false,
  double stretchTriggerOffset = 100.0,
  AsyncCallback? onStretchTrigger,
  ShapeBorder? shape,
  double toolbarHeight = kToolbarHeight,
  double? leadingWidth,
  TextStyle? toolbarTextStyle,
  TextStyle? titleTextStyle,
  SystemUiOverlayStyle? systemOverlayStyle,
  bool forceMaterialTransparency = false,
  Clip? clipBehavior
})

Let's take a closer look at each parameter and its purpose:

  • key: An optional key that uniquely identifies this widget.

  • leading: Widget to display before the title.

  • automaticallyImplyLeading: Whether to automatically show the leading widget if leading is null.

  • title: The primary widget displayed in the app bar.

  • actions: List of widgets to display after the title.

  • flexibleSpace: A widget that appears behind the toolbar and can expand/contract.

  • bottom: A widget to be placed below the toolbar.

  • elevation: The elevation of the app bar when it is pinned.

  • scrolledUnderElevation: The elevation of the app bar when it is not pinned.

  • shadowColor: The color of the shadow that is displayed when the app bar is floating.

  • surfaceTintColor: The color of the surface on which the app bar is displayed.

  • forceElevated: Forces the app bar to always have a shadow, regardless of floating or pinned state.

  • backgroundColor: The background color of the app bar.

  • foregroundColor: The foreground color, including text and icons.

  • iconTheme: The icon theme for icons in the app bar.

  • actionsIconTheme: The icon theme for icons in the actions list.

  • primary: Whether this app bar is the primary app bar (used in NestedScrollView).

  • centerTitle: Whether to center the title.

  • excludeHeaderSemantics: Whether to exclude the app bar from the semantic tree.

  • titleSpacing: The spacing between the title and the leading widget.

  • collapsedHeight: The height of the app bar when it is collapsed.

  • expandedHeight: The height of the app bar when it is fully expanded.

  • floating: Whether the app bar should become visible as soon as the user scrolls down.

  • pinned: Whether the app bar should remain visible at the top after scrolling.

  • snap: Whether the app bar should snap into place when scrolling ends.

  • stretch: Whether the flexible space should stretch to fill the available space.

  • stretchTriggerOffset: The offset to trigger the stretch effect.

  • onStretchTrigger: Callback when the stretch effect is triggered.

  • shape: The shape of the app bar.

  • toolbarHeight: The height of the toolbar portion of the app bar.

  • leadingWidth: The width of the leading widget.

  • toolbarTextStyle: The text style for the title and leading widgets.

  • titleTextStyle: The text style for the title widget.

  • systemOverlayStyle: The overlay style for the system UI elements (status bar, etc.).

  • forceMaterialTransparency: Forces the app bar to have material-like transparency.

  • clipBehavior: The clipping behavior applied to the app bar's content.

Importing necessary libraries

Before using the SliverAppBar widget, make sure to import the required libraries in our Dart file:

import 'package:flutter/material.dart';

Implementing SliverAppBar

The most basic setup for the SliverAppBar involves wrapping it within a CustomScrollView. A CustomScrollView allows us to combine multiple Slivers to create more complex scrolling behaviors.

class MySliverAppBarScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
// App bar configurations go here
// Example: title, actions, floating, pinned, etc.
),
// Other slivers go here
],
),
);
}
}

Configuring the SliverAppBar

Now, let's see how we can configure the SliverAppBar with some common properties:

Title and actions

The title property allows us to set the title of the app bar and the actions property is used to place action buttons on the app bar.

SliverAppBar(
title: Text('Educative Sliver App bar'),
actions: [
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
// Add your action here
},
),
// Add more actions as needed
],
)

Collapsing behavior

The SliverAppBar can collapse and expand based on the user's scrolling direction. To enable this, set the floating and pinned properties. The floating property will make the app bar smoothly appear and disappear during scrolling, while the pinned property will keep a portion of the app bar visible at all times.

SliverAppBar(
title: Text('Educative Sliver App bar'),
floating: true,
pinned: true,
)

Flexible space and colors

The flexibleSpace property allows us to add flexible content behind the app bar, such as an image or a custom widget, and we can also customize the background and foreground color of the app bar.

SliverAppBar(
title: Text('Educative Sliver App bar'),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
flexibleSpace: Image.network(
'https://example.com/image.jpg',
fit: BoxFit.cover,
),
)

Code example

We get the following output by putting together the code explained above.

import 'package:flutter/material.dart';

/// Flutter code sample for [SliverAppBar].

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

class AppBarApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      home: SliverAppBarExample(),
    );
  }
}

class SliverAppBarExample extends StatefulWidget {

  @override
  State<SliverAppBarExample> createState() => _SliverAppBarExampleState();
}

class _SliverAppBarExampleState extends State<SliverAppBarExample> {
  bool _pinned = true;
  bool _snap = false;
  bool _floating = false;

// [SliverAppBar]s are typically used in [CustomScrollView.slivers], which in
// turn can be placed in a [Scaffold.body].
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            pinned: _pinned,
            snap: _snap,
            floating: _floating,
            expandedHeight: 160.0,
            flexibleSpace: const FlexibleSpaceBar(
              title: Text('SliverAppBar'),
              background: FlutterLogo(),
            ),
          ),
          const SliverToBoxAdapter(
            child: SizedBox(
              height: 20,
              child: Center(
                child: Text('Scroll to see the SliverAppBar in effect.'),
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Container(
                  color: index.isOdd ? Colors.white : Colors.black12,
                  height: 100.0,
                  child: Center(
                    child: Text('$index', textScaleFactor: 5),
                  ),
                );
              },
              childCount: 20,
            ),
          ),
        ],
      ),
      bottomNavigationBar: BottomAppBar(
        child: Padding(
          padding: const EdgeInsets.all(8),
          child: OverflowBar(
            overflowAlignment: OverflowBarAlignment.center,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  const Text('pinned'),
                  Switch(
                    onChanged: (bool val) {
                      setState(() {
                        _pinned = val;
                      });
                    },
                    value: _pinned,
                  ),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  const Text('snap'),
                  Switch(
                    onChanged: (bool val) {
                      setState(() {
                        _snap = val;
                        // Snapping only applies when the app bar is floating.
                        _floating = _floating || _snap;
                      });
                    },
                    value: _snap,
                  ),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  const Text('floating'),
                  Switch(
                    onChanged: (bool val) {
                      setState(() {
                        _floating = val;
                        _snap = _snap && _floating;
                      });
                    },
                    value: _floating,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • Line 3570: Inside the CustomScrollView, add a SliverAppBar widget. It is the app bar that can be scrolled out of view.

  • Lines 3746: Configure the SliverAppBar with properties like pinned, snap, floating, and

  • expandedHeight. It also has a FlexibleSpaceBar containing title and a FlutterLogo as the background.

  • Lines 4754: Add a SliverToBoxAdapter to display a message asking the user to scroll and see the effect of the SliverAppBar.

  • Lines 5570: Add a SliverList with a SliverChildBuilderDelegate. This creates a list of containers with alternating colors, each containing a centered text.

  • Lines 71125:Add a BottomAppBar to the Scaffold, containing a Padding widget with an OverflowBar widget as a child.

  • Lines 74123: The OverflowBar displays a row with switches for three options: _pinned, _snap, and _floating. These options control the behavior of the SliverAppBar (whether it stays pinned, snaps, or floats). The onChanged callbacks of the switches update the states of _pinned, _snap, and _floating when their values change, causing the SliverAppBar behavior to change accordingly.

Conclusion

The SliverAppBar in Flutter provides a collapsible and flexible app bar for dynamic scrolling behavior. Its parameters allow titles, actions, colors, elevation, and more customization. Combined with other slivers, it creates impressive scrolling effects in Flutter apps.

Copyright ©2024 Educative, Inc. All rights reserved