Cómo centrar el título de una barra de aplicaciones

113

Estoy tratando de centrar el texto del título en una barra de aplicaciones que tiene acciones iniciales y finales.

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

Esto funciona bien, excepto que el título está alineado a la izquierda como se muestra en esta imagen:

TÍTULO A LA IZQUIERDA

Cuando trato de incluir el título en el centro, parece que está demasiado a la izquierda:

@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 NO BIEN CENTRADO

Me encantaría una solución para centrar el texto del título perfectamente entre los 2 iconos.

cristiano
fuente

Respuestas:

309

Centrar el título es lo predeterminado en iOS. En Android, el AppBartítulo de por defecto está alineado a la izquierda, pero puedes anularlo pasando centerTitle: truecomo argumento al AppBarconstructor.

Ejemplo:

AppBar(
  centerTitle: true, // this is all you need
  ...
)
Collin Jackson
fuente
6
en este caso, el título no aparece exactamente en el centro: /
Esto ni siquiera afecta la alineación del título para mí.
Michael Tolsma
13

Tuve el mismo problema y finalmente funcionó cuando agregué
mainAxisSize: MainAxisSize.min a mi widget Row. ¡Espero que esto ayude!

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

En mi caso, quería tener un logo / imagen centrado en lugar de un texto. En este caso, centerTitleno es suficiente (no estoy seguro de por qué, tengo un archivo svg, tal vez esa sea la razón ...), por ejemplo, esto:

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

no centrará realmente la imagen (además, la imagen puede ser demasiado grande, etc.). Lo que me funciona bien es un código como este:

appBar: AppBar(centerTitle: true,
    title: ConstrainedBox(
        constraints: BoxConstraints(maxHeight: 35, maxWidth: 200),
        child: AppImages.logoSvg)),
Simon Mourier
fuente
La respuesta aceptada funciona para el texto, pero esta es la respuesta correcta para los widgets personalizados. ¡Gracias!
sfratini
¡Trabajó para mi! Parece que centerTitle no funciona correctamente cuando hay acciones en la barra de herramientas. Éste lo arregló.
Moti Bartov
No tiene otro efecto para mí que la solución más simple. En mi caso, tener un espacio de borde transparente alrededor de la imagen conduce a una ubicación incorrecta. Simplemente recortando la imagen un poco más ajustada hizo que la solución simple funcionara.
rgisi
8

Así es como hago centerTitle en mi barra de aplicaciones:

@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(),
      ),
   ) 
);
}
Wildan Pratama
fuente
2

Después de probar muchas soluciones, esto me ayudó a centerTitle: true agregar un código de muestra además de la respuesta de @Collin Jackson

Ejemplo enbuild(BuildContext context)

hacer esto

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
      ),
Aprende rápido
fuente
1
Ha pasado un tiempo, esto resolvió el problema. Muy simple. Gracias.
Ravimaran
2

Aquí hay un enfoque diferente si desea crear un título de barra de aplicación personalizado. Por ejemplo, desea una imagen y un texto en el centro de la barra de la aplicación y luego agregue

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'))
            ],

          ),
  )

Aquí hemos creado un Rowcon MainAxisAlignment.centerpara centrar a los niños. Luego, hemos agregado dos hijos: un icono y otro Containercon texto. Envolví el Textwidget en el Containerpara agregar el relleno necesario.

Annsh Singh
fuente
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"),
    );
}
Saman Missaghian
fuente
0

Esto puede ayudar a crear el texto del título de la barra de aplicaciones en el centro. Puede elegir agregar los estilos que desee usando Estilo o comentarlo si no es necesario.

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

En la pantalla de la aplicación:

ingrese la descripción de la imagen aquí

Rahul Shyokand
fuente
0

Puede centrar el título de una barra de aplicaciones mediante el parámetro centerTitle .

centerTitle es un tipo de datos booleano y el valor predeterminado es Falso.

centerTitle : verdadero

Ejemplo:

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('App Title'),
          backgroundColor: Colors.red,
          centerTitle: true,
        ),
      ),
    ),
  );
}

ingrese la descripción de la imagen aquí

Kranthi
fuente
0

appbar: AppBar (centerTitle: true, title: Text ("HOLA"))

Musfiq Shanta
fuente
-2

Usar Centerobjeto

    appBar: AppBar(
      title: Center(
        child: const Text('Title Centered')
      )
    )
Andrei Todorut
fuente
-3
appBar: AppBar(
    mainAxisAlignment: MainAxisAlignment.center,
)
Issa
fuente