Come centrare il titolo di un'appbar


111

Sto cercando di centrare il testo del titolo in una barra dell'app che ha sia un'azione iniziale che una finale.

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

Funziona bene tranne che il titolo è allineato a sinistra come mostrato in questa immagine:

TITOLO A SINISTRA

Mentre provo a includere il titolo al centro, sembra che sia troppo a sinistra:

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

TITOLO NON BEN CENTRATO

Mi piacerebbe una soluzione per ottenere il testo del titolo perfettamente centrato tra le 2 icone.

Risposte:


295

Centrare il titolo è l'impostazione predefinita su iOS. Su Android, il AppBartitolo di è allineato a sinistra per impostazione predefinita, ma puoi sovrascriverlo passando centerTitle: truecome argomento al AppBarcostruttore.

Esempio:

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

5
in questo caso il titolo non appare esattamente al centro: /

Questo non influisce nemmeno sull'allineamento del titolo per me.
Michael Tolsma

12

Ho avuto lo stesso problema e alla fine ha funzionato quando ho aggiunto
mainAxisSize: MainAxisSize.min al mio widget Row. Spero che aiuti!

 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

Nel mio caso volevo avere un logo / un'immagine centrata invece di un testo. In questo caso, centerTitlenon è abbastanza (non so perché, ho un file svg, forse è questo il motivo ...), quindi ad esempio questo:

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

non centrerà realmente l'immagine (inoltre l'immagine può essere troppo grande, ecc.). Quello che funziona bene per me è un codice come questo:

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

La risposta accettata funziona per il testo, ma questa è la risposta giusta per i widget personalizzati. Grazie!
sfratini

Ha funzionato per me! Sembra che centerTitle non funzioni correttamente quando ci sono azioni sulla barra degli strumenti. Questo l'ha risolto.
Moti Bartov

Non ha altro effetto per me che la soluzione più semplice. Nel mio caso, avere uno spazio del bordo trasparente attorno all'immagine porta a un posizionamento errato. Il semplice taglio dell'immagine un po 'più stretto ha fatto funzionare la semplice soluzione.
rgisi

8

Ecco come creo centerTitle sulla mia appbar:

@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

Dopo aver provato molte soluzioni, questo mi ha aiutato ad centerTitle: true aggiungere codice di esempio oltre alla risposta di @Collin Jackson

Esempio inbuild(BuildContext context)

Fai questo

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
È passato un po 'di tempo, questo ha risolto il problema. Molto semplice. Grazie.
Ravimaran

2

Ecco un approccio diverso se desideri creare un titolo della barra dell'app personalizzato. Ad esempio, vuoi un'immagine e un testo al centro della barra dell'app, quindi aggiungi

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

          ),
  )

Qui abbiamo creato un Rowcon MainAxisAlignment.centerper centrare i bambini. Quindi abbiamo aggiunto due figli: un'icona e una Containercon testo. Ho inserito il Textwidget nel Containerper aggiungere il riempimento necessario.


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

Questo può aiutare a creare il testo del titolo dell'appbar nel centro. Puoi scegliere di aggiungere gli stili desiderati usando lo stile o commentarlo se non necessario.

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

Sul display dell'app:

inserisci qui la descrizione dell'immagine


-2

Usa Centeroggetto

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

-2
appBar: AppBar(
    mainAxisAlignment: MainAxisAlignment.center,
)
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.