小编典典

如何将应用栏标题居中

flutter

我正在尝试将标题文本放在具有前后动作的应用栏中。

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

标题不正确

我希望找到一种解决方案,以使标题文本在两个图标之间完美居中。


阅读 310

收藏
2020-08-13

共1个答案

小编典典

标题居中是iOS上的默认设置。在Android上,AppBar的标题默认为左对齐,但您可以通过将其centerTitle: true作为参数传递给AppBar构造函数来覆盖它。

例:

AppBar(
  centerTitle: true, // this is all you need
  ...
)
2020-08-13