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:
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.
);
}
I would love a solution to get the title text centered perfectly between the 2 icons.
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
...
)
I had the same problem and it finally worked when I added the
mainAxisSize: MainAxisSize.min to my Row widget. I hope this helps!
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: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
widget.title,
),
],
),
leading: new IconButton(
icon: new Icon(Icons.accessibility),
onPressed: () {},
),
actions: [
menuButton,
],
),
);
}