Подтвердить что ты не робот

Как центрировать заголовок панели приложений

Я пытаюсь центрировать текст заголовка в панели приложений, которая имеет как ведущие, так и завершающие действия.

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

Это хорошо работает, за исключением того, что название выравнивается слева, как показано на этом рисунке:

TITLE TO THE LEFT

Как я пытаюсь включить заголовок в центре, кажется, что он слишком много влево:

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

TITLE NOT WELL CENTERED

Мне понравилось бы решение получить текст заголовка, идеально расположенный между двумя значками. Большое спасибо,

4b9b3361

Ответ 1

Центрирование заголовка по умолчанию на iOS. В Android заголовок AppBar по умолчанию выровнен по левому краю, но вы можете переопределить его, передав centerTitle: true в качестве аргумента конструктору AppBar.

Пример:

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

Ответ 2

Вот как я делаю centerTitle на моей панели приложений:

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

Ответ 3

У меня была такая же проблема, и она, наконец, работала, когда я добавил
mainAxisSize: MainAxisSize.min для моего виджета Row. Надеюсь, это поможет!

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

Ответ 4

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

Ответ 5

После многих попыток это помогло мне centerTitle: true добавление примера кода в дополнение к ответу @Collin Jackson

Пример в build(BuildContext context)

сделать это

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

Ответ 6

Вот другой подход, если вы хотите создать собственное название панели приложений. Например, вы хотите изображение и текст в центре панели приложений, а затем добавьте

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

          ),
  )

Здесь мы создали Строка с MainAxisAlignment.center, чтобы центрировать детей. Затем мы добавили двое детей - значок и контейнер с текстом. Я завернул текстовый виджет в контейнере, чтобы добавить необходимое дополнение.

Надеюсь, что это поможет.

Ответ 7

Вы можете поместить заголовок в контейнер и установить выравнивание по центру

Ответ 8

Использовать объект Center

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