How to change width of AppBar() in Flutter?

Issue

I want to reuse mobile app code for flutter web. I already coded with AppBar() and body widgets in scaffold in all screens. Now i am taking 400 width and center for web, it is good except appbar.

        Scaffold(
        appBar: this.getAppBarWidget(),
        body: Center(
          child: Container(
            width: kIsWeb ? 400.0 : MediaQuery.of(context).size.width,
            child: this.getBodyWidget(),
          ),
        ))

Above code is perfectly working for all screens of mobile and web except appbar in web.

How do i change width of appbar to fit width 400 ?

If i use Size.fromWidth(400) getting error.

Below code is working for mobile and web.

   Scaffold(
    body: Center(
  child: Container(
    width: kIsWeb ? 400.0 : MediaQuery.of(context).size.width,
    child: Column(
      children: [
        this.getCustomAppbarWidget(),
        this.getBodyWidget(),
      ],
    ),
  ),
))

Please suggest me.

Solution

The size this widget would prefer if it were otherwise unconstrained.
In many cases it’s only necessary to define one preferred dimension. For example the [Scaffold] only depends on its app bar’s preferred height. In that case implementations of this method can just return new Size.fromHeight(myAppBarHeight).

But we can provide customAppBar like

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Container(
        alignment: Alignment.center,
        color: Colors.pink,
        // we can set width here with conditions
        width: 200,
        height: kToolbarHeight,
        child: Text("MY AppBar"),
      ),
    );
  }

  ///width doesnt matter
  @override
  Size get preferredSize => Size(200, kToolbarHeight);
}

and use

Scaffold(
      extendBodyBehindAppBar: true,
      appBar: MyAppBar(),
      body: ......

if it cover the 1st item of body, and in this case use SizedBox(height: kToolbarHeight) to handle the situation if needed.
Result

enter image description here

Answered By – Yeasin Sheikh

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *