How To Create Expandable And Collapsing Header In Flutter App

admin_img Posted By Bajarangi soft , Posted On 29-10-2020

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.

How To Create Expandable And Collapsing Header In Flutter App

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.
Expandable And Collapsing Header

import 'package:flutter/material.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Expandable Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ScrollingHeaderExample(),
    );
  }
}

class ScrollingHeaderExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
        title: 'Expanding & Collapsing Header',
        home: MainScreen()
    );
  }
}
/// This is the stateless widget that the main application instantiates.
class MainScreen extends StatelessWidget {
  final data=['Mango','Apple','Banana','SweetPear','Lemon','Potato', 'Gazar', 'Chilli', 'Orange','Musterd Greeen', 'Pear'];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
        body: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              pinned: true,
              expandedHeight: 250.0,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('Collapsing Header',style: TextStyle(fontSize: 14),),
                background: Image.asset(
                  "assets/images/images.jpg",
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                  return Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Container(
                      height: 20,
                      child: Text('${data[index]}',style: TextStyle(color: Colors.white),),
                    ),
                  );
                },
                childCount: data.length,
              ),

            ),
          ],
        )
    );
  }
}

Related Post