Search code examples
flutterflutter-layoutflutter-sliverappbar

How to change the alignment of the title of the SliverAppBar?


How to change the alignment of the title in the SliverAppBar when the app bar is expanded? I want to make the title's alignment to the left of the bottom when the app bar is expanded and change it to center when the app bar is collapsed. I tried LayoutBuilder, but I don't know how to check if the app bar is expanded or not.


Solution

  • You can use this as pskink menthioned

    class AppSliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
      @override
      Widget build(
          BuildContext context, double shrinkOffset, bool overlapsContent) {
        return Container(
          height: maxExtent,
          color: Colors.deepPurple,
          child: LayoutBuilder(
            builder: (context, constraints) => Stack(
              children: [
                  Align(
                  alignment: Alignment.lerp(const Alignment(-.95, 0),
                      const Alignment(0, 0), shrinkOffset / maxExtent)!,
                  child: Text("Title"),
                ),
              ],
            ),
          ),
        );
      }
    
      @override
      double get maxExtent => 200;
    
      @override
      double get minExtent => kToolbarHeight;
    
      @override
      bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
          false;
    }