アプリバーのタイトルを中央に配置する方法 質問する

アプリバーのタイトルを中央に配置する方法 質問する

先頭アクションと末尾アクションの両方を持つアプリ バーでタイトル テキストを中央に配置しようとしています。

@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.
  );
}

これは、次の図に示すようにタイトルが左揃えになっている点を除けば、うまく機能します。

タイトルは左

タイトルを中央に配置しようとすると、左に寄りすぎているように見えます。

@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.
  );
}

タイトルが中央に配置されていません

タイトル テキストを 2 つのアイコンの中央にぴったり配置できるソリューションがあれば嬉しいです。

ベストアンサー1

iOS では、タイトルを中央揃えにするのがデフォルトです。Android では、AppBarのタイトルはデフォルトで左揃えになりますが、コンストラクターcenterTitle: trueに引数として渡すことでこれをオーバーライドできますAppBar

例:

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

おすすめ記事