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

Стиль BottomNavigationBar в Flutter

Я пробовал Flutter, и я пытаюсь изменить цвет BottomNavigationBar в приложении, но все, что я мог достигнуть, это изменить цвет объекта BottomNavigationItem (значок и текст).

Вот где я объявляю свой BottomNavigationBar:

class _BottomNavigationState extends State<BottomNavigationHolder>{

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: null,
      body: pages(),
      bottomNavigationBar:new BottomNavigationBar(
        items: <BottomNavigationBarItem>[
          new BottomNavigationBarItem(
              icon: const Icon(Icons.home),
              title: new Text("Home")
          ),
          new BottomNavigationBarItem(
              icon: const Icon(Icons.work),
              title: new Text("Self Help")
          ),
          new BottomNavigationBarItem(
              icon: const Icon(Icons.face),
              title: new Text("Profile")
          )
        ],
        currentIndex: index,
        onTap: (int i){setState((){index = i;});},
        fixedColor: Colors.white,
      ),
    );
  }

Раньше я думал, что я понял, что редактирование canvasColor на зеленый на моей основной теме приложения, но это испортило всю цветовую схему приложения:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
        canvasColor: Colors.green
      ),
      home: new FirstScreen(),
    );
  }
}
4b9b3361

Ответ 1

BottomNavigationBar указать цвет фона BottomNavigationBar но изменить canvasColor. Один из способов добиться этого, не испортив все приложение, - это обернуть BottomNavigationBar в Theme с желаемым canvasColor.

Пример:

  bottomNavigationBar: new Theme(
    data: Theme.of(context).copyWith(
        // sets the background color of the 'BottomNavigationBar'
        canvasColor: Colors.green,
        // sets the active color of the 'BottomNavigationBar' if 'Brightness' is light
        primaryColor: Colors.red,
        textTheme: Theme
            .of(context)
            .textTheme
            .copyWith(caption: new TextStyle(color: Colors.yellow))), // sets the inactive color of the 'BottomNavigationBar'
    child: new BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      currentIndex: 0,
      items: [
        new BottomNavigationBarItem(
          icon: new Icon(Icons.add),
          title: new Text("Add"),
        ),
        new BottomNavigationBarItem(
          icon: new Icon(Icons.delete),
          title: new Text("Delete"),
        )
      ],
    ),
  ),

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

Ответ 2

Попробуйте обернуть BottomNavigationBar в Container затем установить его color.

Пример:

@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: null,
      body: pages(),
      bottomNavigationBar:new Container(
        color: Colors.green,
        child: BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            new BottomNavigationBarItem(
                icon: const Icon(Icons.home),
                title: new Text("Home")
            ),
            new BottomNavigationBarItem(
                icon: const Icon(Icons.work),
                title: new Text("Self Help")
            ),
            new BottomNavigationBarItem(
                icon: const Icon(Icons.face),
                title: new Text("Profile")
            )
          ],
        currentIndex: index,
        onTap: (int i){setState((){index = i;});},
        fixedColor: Colors.white,
        ),
      );
    );
  };

Ответ 3

Просто добавьте backgroundColor свойство BottomNavigationBar виджета.

@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: null,
      body: pages(),
      bottomNavigationBar:new BottomNavigationBar(
        items: <BottomNavigationBarItem>[
          new BottomNavigationBarItem(
              icon: const Icon(Icons.home),
              title: new Text("Home")
          ),
          new BottomNavigationBarItem(
              icon: const Icon(Icons.work),
              title: new Text("Self Help")
          ),
          new BottomNavigationBarItem(
              icon: const Icon(Icons.face),
              title: new Text("Profile")
          )
        ],
        currentIndex: index,
        onTap: (int i){setState((){index = i;});},
        fixedColor: Colors.white,
        backgroundColor: Colors.black45,
      ),
    );
  }

Ответ 4

Принятый ответ не совсем неверен. Однако BottomNavigationBar фактически имеет свойство backgroundColor. Согласно документации

Если type имеет тип BottomNavigationBarType.shifting и itemss, для которого установлено значение BottomNavigationBarItem.backgroundColor, элемент backgroundColor будет выплескивать и перезаписывать этот цвет.

Это означает, что backgroundColor BottomNavigation будет переопределен отдельными элементами backgroundColor, поскольку типом по умолчанию является BottomNavigationBarType.shifting.

Чтобы это исправить, просто добавьте следующее свойство в объявленный виджет BottomNavigationbar.

type: BottomNavigationBarTyle.fixed,

Примечание. Однако если вам нужен эффект смещения, вам придется объявлять цвета для каждого элемента или обернуть виджет, который позволяет переопределять цвет фона дочернего виджета.

то есть Somethign как Container виджет.

Ответ 5

Раньше не было прямого способа установить цвета, но теперь вы можете использовать.

BottomNavigationBar(
  backgroundColor: Colors.grey[900],
  selectedItemColor: Colors.green,
  unselectedItemColor: Colors.grey,
  ...
)