Search code examples
flutterdart

How to center the title of an appbar


I'm trying to center the title text in an app bar that has both a leading and trailing actions.

@override
Widget build(BuildContext context) {
  final menuButton = new PopupMenuButton<int>(
    onSelected: (int i) {},
    itemBuilder: (BuildContext ctx) {},
    child: new Icon(
      Icons.dashboard,
    ),
  );

  return new Scaffold(
    appBar: new AppBar(
      // Here we take the value from the MyHomePage object that
      // was created by the App.build method, and use it to set
      // our appbar title.
      title: new Text(widget.title, textAlign: TextAlign.center),
      leading: new IconButton(
          icon: new Icon(Icons.accessibility),
          onPressed: () {},
      ),
      actions: [
        menuButton,
      ],
    ),
    body: new Center(
      child: new Text(
        'Button tapped $_counter time${ _counter == 1 ? '' : 's' }.',
      ),
    ),
    floatingActionButton: new FloatingActionButton(
      onPressed: _incrementCounter,
      tooltip: 'Increment',
      child: new Icon(Icons.add),
    ), // This trailing comma makes auto-formatting nicer for build methods.
  );
}

This works well except the title is aligned on the left as is shown in this picture:

TITLE TO THE LEFT

As I try to include the title in the center, it appears that it's too much to the left:

@override
Widget build(BuildContext context) {
  final menuButton = new PopupMenuButton<int>(
    onSelected: (int i) {},
    itemBuilder: (BuildContext ctx) {},
    child: new Icon(
      Icons.dashboard,
    ),
  );

  return new Scaffold(
    appBar: new AppBar(
      // Here we take the value from the MyHomePage object that
      // was created by the App.build method, and use it to set
      // our appbar title.
      title: new Center(child: new Text(widget.title, textAlign: TextAlign.center)),
      leading: new IconButton(
          icon: new Icon(Icons.accessibility),
          onPressed: () {},
      ),
      actions: [
        menuButton,
      ],
    ),
    body: new Center(
      child: new Text(
        'Button tapped $_counter time${ _counter == 1 ? '' : 's' }.',
      ),
    ),
    floatingActionButton: new FloatingActionButton(
      onPressed: _incrementCounter,
      tooltip: 'Increment',
      child: new Icon(Icons.add),
    ), // This trailing comma makes auto-formatting nicer for build methods.
  );
}

TITLE NOT WELL CENTERED

I would love a solution to get the title text centered perfectly between the 2 icons.


Solution

  • Centering the title is the default on iOS. On Android, the AppBar's title defaults to left-aligned, but you can override it by passing centerTitle: true as an argument to the AppBar constructor.

    Example:

    AppBar(
      centerTitle: true, // this is all you need
      ...
    )