flutterflutter-appbarpreferredsize

Why is the Scaffold content in my Flutter app not going under my custom AppBar?


When I use a regular AppBar in a Scaffold, all of the content is pushed down so it's not covered. However, now that I created a custom FloatingAppBar, the content goes under the app bar even though I'm using it the same way. Also, since the FloatingAppBar has to implement PreferredSizeWidget, I also have to give it a preferred size from the height which makes the height of the app bar very small when I use it in a bottom modal widget. Is there any way to get around that? Here is a screenshot of the issue and the code for the custom app bar:

Floating app bar covers content

import 'package:flutter/material.dart';

class FloatingAppBar extends StatelessWidget implements PreferredSizeWidget {
  const FloatingAppBar(
      {Key? key,
      required this.title,
      required this.leading,
      required this.actions})
      : super(key: key);

  final Widget leading;
  final Widget title;
  final List<Widget> actions;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(40),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(40),
        child: Container(
          color: const Color(0xFFd3d8e9),
          height: 120,
          child: Center(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  leading,
                  title,
                  Row(
                    children: actions,
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(120);
}

Solution

  • The reason of this issue is that you set the appbar height 120, but the actual height you give to appbar is 120 + padding top + padding bottom. in order to fix it , you could do this:

    Size get preferredSize => const Size.fromHeight(120 + 40 + 40);
    

    For your color issue, because you know the app bar height 120 in this case, you can add top padding to your scaffold body to fix the background color issue.