Home > Net >  Switch to a different app bar on scroll flutter
Switch to a different app bar on scroll flutter

Time:12-15

I have an custom app bar which I created using various widgets. The app bar has a background image and some buttons like follow, about etc.

I used it in the page like this:

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(180),
        child: SafeArea(
          child: SingleMerchantAppBar(),
        ),
      ),
      extendBody: false,
      body: SingleChildScrollView(
        child: _buildItems(context),
      ),
      floatingActionButton: ChatButton(),
    );
  }

My custom app bar: SingleMerchantAppBar. But I need to change the entire app bar when the user scrolls up.

Let's call the second app bar AnotherSingleMerchantAppBar. This app is pretty similar to the default app bar but with no background image and changes in button colors.

My SingleMerchantAppBar can be found enter image description here

After scroll app bar:

enter image description here

I tried sliver app bar but it makes the app bar small and only the text remains as from the examples I've seen so far.

CodePudding user response:

You need a ScrollController to listen, when a User is scrolling. For example:

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

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

class _ChangingAppBarState extends State<ChangingAppBar> {
  ScrollController _scrollController = ScrollController();
  double _scrollPosition = 0;

  _scrollListener() {
    setState(() {
      _scrollPosition = _scrollController.position.pixels;
    });
  }

  @override
  void initState() {
    _scrollController.addListener(_scrollListener);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _scrollPosition == 0
          ? AppBar(
              title: const Text('1st AppBar'),
              backgroundColor: Colors.red,
            )
          : AppBar(
              title: const Text('2nd AppBar'),
              backgroundColor: Colors.blue,
            ),
      body: ListView.builder(
        controller: _scrollController,
        itemCount: 20,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text('Item: $index'),
          );
        },
      ),
    );
  }
}
  • Related