How to Create Expanding and Collapsing Header in Flutter

Expanding and collapsing headers look beautiful when you have a list of things which the user scroll through. Unlike other mobile app development platforms, creating expanding and collapsing header in flutter is easy.

We need the help of multiple widgets to create the header. As we are trying to create a scrolling effect we definitely need CustomScrollView widget. We need SliverAppBar widget which acts as the header of the list. FlexibleSpaceBar widget defines the area which expands, stretches and collapses. The SliverList widget constitutes the remaining portion of scroll view by providing children in a linear array.

Go through the following Flutter example code for more understanding.

import 'package:flutter/material.dart';


class ScrollingHeaderExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Expanding & Collapsing Header',
      home: MainScreen()
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class MainScreen extends StatelessWidget {
  final data=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten'];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
  slivers: <Widget>[
    SliverAppBar(
      pinned: true,
      expandedHeight: 250.0,
      flexibleSpace: FlexibleSpaceBar(
        title: Text('Collapsing Header'),
        background: Image.network(
                      "https://cdn.pixabay.com/photo/2019/12/14/07/21/mountain-4694346_960_720.png",
                      fit: BoxFit.cover,
                    ),
      ),
    ),
    SliverList(
      delegate: SliverChildBuilderDelegate(
       
        (BuildContext context, int index) {
          return Container(
            alignment: Alignment.center,
            height: 100,
            color: Colors.red[100],
            child: Text('${data[index]}'),
          );
        },
         childCount: data.length,
      ),
      
    ),
  ],
)
    );
  }
}

And following is the output of this Flutter tutorial.

I hope this flutter tutorial will help you to create beautiful user interface.

Leave a Comment

Your email address will not be published. Required fields are marked *