颤动中的 BottomNavigationBarItem 背景颜色

Abd*_*aed 6 flutter flutter-test flutter-dependencies flutter-layout

我需要将背景颜色设置为选定的 BottomNavigationBarItem,如下图所示 BottomNavigationBarItem 背景颜色

Pab*_*era 6

无法更改所选项目的背景,BottomNavigationBar因为这不遵循设计指南。

如果您仍然想以这种方式使用它,请按照BottomNavigationBar 类中给出的示例,这里有一个解决方法:

final _selectedItemColor = Colors.white;
final _unselectedItemColor = Colors.white30;
final _selectedBgColor = Colors.indigo;
final _unselectedBgColor = Colors.blue;
int _selectedIndex = 0;
static const TextStyle optionStyle =
    TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
  Text(
    'Index 0: Home',
    style: optionStyle,
  ),
  Text(
    'Index 1: Business',
    style: optionStyle,
  ),
  Text(
    'Index 2: School',
    style: optionStyle,
  ),
];

void _onItemTapped(int index) {
  setState(() {
    _selectedIndex = index;
  });
}

Color _getBgColor(int index) =>
    _selectedIndex == index ? _selectedBgColor : _unselectedBgColor;

Color _getItemColor(int index) =>
    _selectedIndex == index ? _selectedItemColor : _unselectedItemColor;

Widget _buildIcon(IconData iconData, String text, int index) => Container(
      width: double.infinity,
      height: kBottomNavigationBarHeight,
      child: Material(
        color: _getBgColor(index),
        child: InkWell(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(iconData),
              Text(text,
                  style: TextStyle(fontSize: 12, color: _getItemColor(index))),
            ],
          ),
          onTap: () => _onItemTapped(index),
        ),
      ),
    );

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: const Text('BottomNavigationBar Sample'),
    ),
    body: Center(
      child: _widgetOptions.elementAt(_selectedIndex),
    ),
    bottomNavigationBar: BottomNavigationBar(
      selectedFontSize: 0,
      items: <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: _buildIcon(Icons.home, 'Home', 0),
          title: SizedBox.shrink(),
        ),
        BottomNavigationBarItem(
          icon: _buildIcon(Icons.business, 'Business', 1),
          title: SizedBox.shrink(),
        ),
        BottomNavigationBarItem(
          icon: _buildIcon(Icons.school, 'School', 2),
          title: SizedBox.shrink(),
        ),
      ],
      currentIndex: _selectedIndex,
      selectedItemColor: _selectedItemColor,
      unselectedItemColor: _unselectedItemColor,
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)

结果:

BottomNavigationBar 选定的背景