使用单独的背景颜色自定义颤振导航栏/选项卡栏



在选项卡栏和导航栏中,我希望所选选项卡具有与栏其余部分不同的背景。

例如:https://i.stack.imgur.com/sKXyj.jpg

这在颤振中可能吗?

如果您使用的是有状态 Widget,则可以在 on Tap 方法中设置 currentIndex 的状态

  @override
  void initState() {
    super.initState();
    currentIndex = 0;
  }

  BottomNavigationBar(
            backgroundColor: Colors.white,
            type: BottomNavigationBarType.fixed,
            items: <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                backgroundColor: currentIndex == 0 ? Colors.green : Colors.black,
                title: Text('0'),
              ),
              BottomNavigationBarItem(
                backgroundColor: currentIndex == 1 ? Colors.green : Colors.black,
                title: Text('1'),
              ),
            ],
            currentIndex: currentIndex,
            onTap: (int index) {
                  setState(() {
                    currentIndex = index;
                });
                _navigateToPage(index);
            },
          );

import 'package:flutter/material.dart';
class ChangeBottomNavBarTextColor extends StatefulWidget {
  @override
  ChangeBottomNavBarTextColorState createState() {
    return new ChangeBottomNavBarTextColorState();
  }
}
class ChangeBottomNavBarTextColorState
    extends State<ChangeBottomNavBarTextColor> {
  String text = 'Home';

  var curIndex = 0;
  _onTap(int index) {
    setState(() {
      curIndex = index;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Change Bottom Nav Bar Text Color Example"),
      ),
      body: Center(
        child: Text(text,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            )),
      ),
      bottomNavigationBar: BottomNavigationBar(
        selectedItemColor: Colors.red,
        currentIndex: curIndex,
        type: BottomNavigationBarType.fixed,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(
              Icons.home,
            ),
            title: Text("Home", style: TextStyle(color: Colors.teal)),
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.favorite,
            ),
            title: Text("Favorite", style: TextStyle(color: Colors.pink)),
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.person,
            ),
            title: Text("Profile", style: TextStyle(color: Colors.brown)),
          ),
          BottomNavigationBarItem(
            activeIcon: Icon(
              Icons.info,
              color: Colors.red,
            ),
            icon: Icon(
              Icons.settings,
            ),
            title: Text("Settings", style: TextStyle(color: Colors.amber)),
          ),
        ],
        onTap: _onTap,
      ),
    );
  }
}

你可以使用类似的东西。当您单击时,_onTap函数将更改currentIndex。然后selectedItemColor将定义所选索引的颜色。你可以玩任何你想要的颜色。

最新更新