Flutter sticky header

Flutter Sticky Header Example

In Flutter, you can create sticky headers using the SliverAppBar widget along with the CustomScrollView widget. The SliverAppBar widget allows you to create a persistent header that sticks to the top of the screen.

Here’s an example of how you can create a sticky header in Flutter:


import 'package:flutter/material.dart';

void main() {
  runApp(StickyHeaderExample());
}

class StickyHeaderExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              pinned: true,
              title: Text('Sticky Header Example'),
              backgroundColor: Colors.blue,
              expandedHeight: 150,
              flexibleSpace: FlexibleSpaceBar(
                background: Image.asset(
                  'assets/header_image.jpg',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return ListTile(
                    title: Text('Item $index'),
                  );
                },
                childCount: 100,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
  

In this example, we create a StickyHeaderExample class that extends the StatelessWidget class. Inside the build method, we create a CustomScrollView widget as the main content area.

The CustomScrollView widget allows us to have different types of scrollable widgets, such as SliverList and SliverGrid, inside it. In this case, we use the SliverAppBar widget as the first child of the CustomScrollView.

The SliverAppBar widget is configured with the pinned property set to true, which makes the header stick to the top of the screen even when scrolling. We provide a title, background color, and an expanded height for the app bar. In the flexibleSpace property, we add an Image.asset widget to display the header image.

Below the SliverAppBar, we add a SliverList widget that contains a list of items. In this example, we use the SliverChildBuilderDelegate to dynamically create list items with a count of 100.

You can run this example by creating a new Flutter project and replacing the default lib/main.dart file with the code above. Also, make sure to include a header image in the specified location (assets/header_image.jpg) or update the image path accordingly.

Leave a comment