MaheshPeri19
MaheshPeri19

Reputation: 402

How to change width of AppBar() in Flutter?

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.

Upvotes: 1

Views: 7694

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63594

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

Upvotes: 7

HasanToufiqAhamed
HasanToufiqAhamed

Reputation: 971

As i know, width did not allow in AppBar. Only height is allowed in AppBar

toolbarHeight: 60,

But if you want to apply manually width in your AppBar you can wrap your AppBar in Padding component

return Scaffold(
      body: Column(
        children: [
          Container(
            width: kIsWeb? 400 : double.maxFinite,
            child: AppBar(
              title: Text('hello'),
            ),
          ),
          Expanded(child: HomePageOne()), // this expanded is you page body
        ],
      ),
    );

Upvotes: 1

Related Questions