【问题标题】:Change tab icon color on selected更改选定的选项卡图标颜色
【发布时间】:2021-04-08 06:27:58
【问题描述】:

我有带有图标和文本的 TabBar:

child: TabBar(
    labelColor: Colors.white,
    unselectedLabelColor: Colors.grey,
    labelStyle: TextStyle(fontSize: 13.0),
    indicator: BoxDecoration(
        borderRadius: BorderRadius.circular(50), // Creates border
        color: const Color(0xFF62A6E9)),
    tabs: [
        Tab(icon: SvgPicture.asset(
            'assets/trending.svg',
            color: const Color(0xFF71768D),
                width: 15,
                height: 15
        ), text: "Популярное"),
        Tab(icon: SvgPicture.asset(
            'assets/new.svg',
            color: const Color(0xFF71768D),
                width: 15,
                height: 15
        ), text: "Новые"),
        Tab(icon: SvgPicture.asset(
            'assets/comingsoon.svg',
            color: const Color(0xFF71768D),
                width: 15,
                height: 15
        ), text: "Ожидаемые"),
    ],
),

我需要更改选定的标签图标颜色,SvgPicture 具有填充图标的颜色属性

【问题讨论】:

  • 查看此link 以获得解决方案

标签: flutter android-studio dart


【解决方案1】:

您需要为您选择的标签提供一个TabController,并根据TabController的索引,您可以更改颜色。

 TabController _tabController;

 @override
 void initState() {
   super.initState();
  _tabController = new TabController(vsync: this, length: 3);
  _tabController.addListener(_handleTabSelection);
 }

 void _handleTabSelection() {
    setState(() {
     });
 }


TabBar(
 controller: _tabController,
 labelColor: Colors.white,
 unselectedLabelColor: Colors.grey,
 labelStyle: TextStyle(fontSize: 13.0),
 indicator: BoxDecoration(
     borderRadius: BorderRadius.circular(50), // Creates border
     color: const Color(0xFF62A6E9)),
 tabs: [
    Tab(icon: SvgPicture.asset(
        'assets/trending.svg',
        color: _tabController.index == 0
                      ? Colors.black
                      : Color(0xFF71768D),
            width: 15,
            height: 15
     ), text: "Популярное"),
     Tab(icon: SvgPicture.asset(
        'assets/new.svg',
        color: _tabController.index == 1
                      ? Colors.black
                      : Color(0xFF71768D),
            width: 15,
            height: 15
     ), text: "Новые"),
     Tab(icon: SvgPicture.asset(
        'assets/comingsoon.svg',
        color: _tabController.index == 2
                      ? Colors.black
                      : Color(0xFF71768D),
            width: 15,
            height: 15
     ), text: "Ожидаемые"),

编辑:

请同时处理 TabController。

@override
void dispose() {
_tabController.dispose();
super.dispose();
}

【讨论】:

  • 在 null 上调用了 getter 'index'。接收者:null 尝试调用:index
  • 我收到错误在 null 上调用了 getter 'index'。
  • DefaultTabController 中可能有问题?我用它
  • 您的解决方案工作,重新启动 android studio 以正常工作
  • @Elexer 很高兴,我很有帮助!
【解决方案2】:

你写的第一件事就是'const'颜色,这意味着颜色属性不能改变,因为它是解决这个问题的常量:

  1. 创建颜色变量 ex:

    颜色 color1 = 颜色(0xFF71768D); // 对于第一个选项卡 ... 以此类推

  2. TabBar 上有一个属性调用'onTap' 这将具有在单击时更改选项卡颜色的功能.. 例如:

    点击按钮:(){ 设置状态((){ color1 = //新颜色 color2 = //新颜色 // 等等 }) }

【讨论】:

    【解决方案3】:

    您可以使用 selectedItemColor 和 unselectedItemColor 属性,您会在这段代码中找到它们 =>

    class TabsScreen extends StatefulWidget {
      @override
      _TabsScreenState createState() => _TabsScreenState();
    }
    
    class _TabsScreenState extends State<TabsScreen> {
      final BorderStyle borderStyle = BorderStyle.solid;
      final List<Map<String, Object>> _pages = [
       {'page': HomeView(), 'title': 'Doctors'},
       {'page': MyCoursesView(), 'title': 'My Courses'}
      ];
      int _selectedPageIndex = 0;
    
      void _selectPage(int index) {
        setState(() {
          _selectedPageIndex = index;
        });
      }
    
      Future<void> showExitDialogConfirmation(
         BuildContext context,) async {
           await DialogManager.showExitDialog(context);
      }
    
      @override
      Widget build(BuildContext context) {
         return Scaffold(
           appBar: AppBar(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.vertical(
                bottom: Radius.circular(20),
              ),
            ),
            title: Text(_pages[_selectedPageIndex]['title'],
              style: TextStyle(
                color: white,
                fontWeight: FontWeight.w700,
                fontFamily: "Roboto",
                fontStyle: FontStyle.normal,
                fontSize: 25)),
              centerTitle: true,
              actions: [
                FlatButton(
                  onPressed: () async {
                       await showExitDialogConfirmation(context);
                  },
                  child: Icon(
                    Icons.logout, color: white,),
                ),
             ],
           ),
           body: _pages[_selectedPageIndex]['page'],
           bottomNavigationBar: Container(
           decoration: BoxDecoration(
            //  color: Color(0xfff7f7f7),
             border: Border.all(
             color: mainGoldColor, 
             style: borderStyle,
             width: 3.0,
           ),
           borderRadius: BorderRadius.vertical(
             top: Radius.circular(15.0),
           ),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(15.0),
              topRight: Radius.circular(15.0),
            ),
            child: BottomNavigationBar(
            onTap: _selectPage,
            backgroundColor: white, 
            unselectedItemColor: Colors.grey,
            selectedItemColor: mainGreenColor, 
            currentIndex: _selectedPageIndex,
            items: [
              BottomNavigationBarItem(
                icon: Icon(
                  Icons.person,
                  size: 25,
                ),
                title: Text('Doctors',
                    style:
                        TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              ),
              BottomNavigationBarItem(
                icon: Icon(
                  Icons.article,
                  size: 25,
                ),
                title: Text(
                  'My Courses',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                  ),
                ),
              ],
            ),
          ),
         ),
       );
      }
     }
    

    【讨论】:

      【解决方案4】:

      工作解决方案

      在您的情况下,您应该使用tabController 在 TabBar 上进行更多自定义。要获得活动标签,您应该使用_tabController.indexIsChanging 并获得活动索引_tabController.index

      输出

      完整代码:

      
      class CustomTabs extends StatefulWidget {
        final Function onItemPressed;
      
        CustomTabs({
          Key key,
          this.onItemPressed,
        }) : super(key: key);
      
        @override
        _CustomTabsState createState() => _CustomTabsState();
      }
      
      class _CustomTabsState extends State<CustomTabs>
          with SingleTickerProviderStateMixin {
        TabController _tabController;
        int _activeIndex = 0;
      
        @override
        void initState() {
          super.initState();
          _tabController = TabController(
            vsync: this,
            length: 3,
          );
        }
      
        @override
        void dispose() {
          super.dispose();
          _tabController.dispose();
        }
      
        @override
        Widget build(BuildContext context) {
          _tabController.addListener(() {
            if (_tabController.indexIsChanging) {
              setState(() {
                _activeIndex = _tabController.index;
              });
            }
          });
          return Scaffold(
            body: Padding(
              padding: const EdgeInsets.only(top: 25),
              child: TabBar(
                controller: _tabController,
                labelColor: Color(0xFF62A6E9),
                unselectedLabelColor: Colors.black,
                labelStyle: TextStyle(fontSize: 13.0),
                // indicator: BoxDecoration(
                //     borderRadius: BorderRadius.circular(50), // Creates border
                //     color: const Color(0xFF62A6E9)),
                tabs: [
                  Tab(
                      icon: SvgPicture.asset('assets/trending.svg',
                          color: _activeIndex == 0 ? Color(0xFF62A6E9) : Colors.black,
                          width: 25,
                          height: 25),
                      text: "Популярное"),
                  Tab(
                    icon: SvgPicture.asset('assets/new.svg',
                        color: _activeIndex == 1 ? Color(0xFF62A6E9) : Colors.black,
                        width: 25,
                        height: 25),
                    text: "Новые",
                  ),
                  Tab(
                      icon: SvgPicture.asset('assets/comingsoon.svg',
                          color: _activeIndex == 2 ? Color(0xFF62A6E9) : Colors.black,
                          width: 25,
                          height: 25),
                      text: "Ожидаемые"),
                ],
              ),
            ),
          );
        }
      }
      
      

      【讨论】:

      • 在 null 上调用了方法“addListener”。接收者:null 尝试调用:addListener(Closure: () => Null)
      • @Elexer 复制粘贴代码。正如您从输出中看到的那样,它在我的情况下是有效的。尝试运行flutter clean 并重新启动您的应用
      • @Elexer 上面的代码更专业地解决了您的问题
      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多