Como centralizar o título de uma barra de aplicativos


111

Estou tentando centralizar o texto do título em uma barra de aplicativos que tem ações iniciais e finais.

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

Isso funciona bem, exceto que o título está alinhado à esquerda, conforme mostrado nesta imagem:

TÍTULO À ESQUERDA

Quando tento incluir o título no centro, parece que está muito à esquerda:

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

TÍTULO NÃO BEM CENTRADO

Eu adoraria uma solução para centralizar perfeitamente o texto do título entre os 2 ícones.

Respostas:


295

Centralizar o título é o padrão no iOS. No Android, o AppBartítulo do padrão é alinhado à esquerda, mas você pode substituí-lo passando centerTitle: truecomo um argumento para o AppBarconstrutor.

Exemplo:

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

5
neste caso, o título não aparece exatamente no centro: /

Isso nem mesmo afeta o alinhamento do título para mim.
— Michael Tolsma

12

Eu tive o mesmo problema e finalmente funcionou quando adicionei
mainAxisSize: MainAxisSize.min ao meu widget Row. Eu espero que isso ajude!

 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,
        ],
      ),
    );
  }

9

No meu caso, eu queria ter um logotipo / imagem centralizado em vez de um texto. Nesse caso, centerTitlenão é suficiente (não tenho certeza porque, eu tenho um arquivo svg, talvez seja esse o motivo ...), então por exemplo, este:

appBar: AppBar(centerTitle: true, title: AppImages.logoSvg)

não centralizará realmente a imagem (além disso, a imagem pode ser muito grande, etc.). O que funciona bem para mim é um código como este:

appBar: AppBar(centerTitle: true,
    title: ConstrainedBox(
        constraints: BoxConstraints(maxHeight: 35, maxWidth: 200),
        child: AppImages.logoSvg)),

A resposta aceita funciona para texto, mas é a resposta certa para widgets personalizados. Obrigado!
— sfratini

Funcionou para mim! Parece que centerTitle não funciona corretamente quando há ações na barra de ferramentas. Este consertou.
— Moti Bartov

Não tem outro efeito para mim do que a solução mais simples. No meu caso, ter um espaço de borda transparente ao redor da imagem leva ao posicionamento incorreto. Simplesmente cortar a imagem um pouco mais apertada fez a solução simples funcionar.
— rgisi

8

Aqui está como faço centerTitle na minha barra de aplicativos:

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: new AppBar(
    centerTitle: true ,
    title: new Text("Login"),
  ),
  body: new Container(
    padding: EdgeInsets.all(18.0),
      key: formkey,
        child: ListView(
        children: buildInputs() + buildSubmitButton(),
      ),
   ) 
);
}

2

Depois de tentar muitas soluções, isso me ajudou a centerTitle: true adicionar código de amostra, além da resposta de @Collin Jackson

Exemplo embuild(BuildContext context)

faça isso

appBar: 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: Text(widget.title),centerTitle: true
      ),

1
Já faz um tempo, isso resolveu o problema. Muito simples. Obrigado.
— Ravimaran

2

Aqui está uma abordagem diferente se você deseja criar um título de barra de aplicativo personalizado. Por exemplo, você quer uma imagem e um texto no centro da barra do aplicativo e, em seguida, adicione

appBar: AppBar(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.your_app_icon,
                color: Colors.green[500],
              ),
              Container(
                  padding: const EdgeInsets.all(8.0), child: Text('YourAppTitle'))
            ],

          ),
  )

Aqui criamos um Rowcom MainAxisAlignment.centerpara centrar as crianças. Em seguida, adicionamos dois filhos - um ícone e um Containercom texto. Envolvi o Textwidget no Containerpara adicionar o preenchimento necessário.


1
@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text('Title'),
            actions: <Widget> [
               IconButton(icon: const Icon(Icons.file_upload), onPressed: _pressed),
            ],
            leading: IconButton(icon: const Icon(Icons.list), onPressed: _pressed),
            centerTitle: true,
        )
        body: Text("Content"),
    );
}

0

Isso pode ajudar a fazer o texto do título da Appbar no Centro. Você pode escolher adicionar seus estilos desejados usando Estilo ou comentá-los se não for necessário.

appBar: AppBar(
          title:  const Center(
            child: Text(
              "App Title",
              style: TextStyle( color: Colors.white,fontSize: 20),
            ),
          ),
        ),

Na tela do aplicativo:

insira a descrição da imagem aqui


-2

CenterObjeto de uso

    appBar: AppBar(
      title: Center(
        child: const Text('Title Centered')
      )
    )

-2
appBar: AppBar(
    mainAxisAlignment: MainAxisAlignment.center,
)
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.