【问题标题】:Changing active color of bottom navigation bar icon更改底部导航栏图标的活动颜色
【发布时间】:2021-03-14 22:59:40
【问题描述】:

所以我尝试在 Flutter 中制作一个底部导航栏,一切正常,除了我希望单击图标时每个图标的颜色不同。到目前为止,每个图标都是蓝色的。设置 color 属性将其永久更改为该颜色,而不仅仅是在活动时。我尝试过使用自定义 IconThemeData 小部件,但这似乎也没有奏效。

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() {
  runApp(TestApp());
}

class TestApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(),
      bottomNavigationBar: BottomNavigationBar(
        showSelectedLabels: false,
        showUnselectedLabels: false,
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        items: [
          BottomNavigationBarItem(
            icon: IconTheme(
              data: IconThemeData(color: Colors.yellow),
              child: Icon(Icons.home),
            ),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.book),
            label: 'Study',
          ),
          BottomNavigationBarItem(
            icon: FaIcon(FontAwesomeIcons.userGraduate),
            label: 'Profile',
          ),
          BottomNavigationBarItem(
            icon: FaIcon(FontAwesomeIcons.store),
            label: 'Shop',
          ),
        ],
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}

【问题讨论】:

  • 哦,对不起,我误会了。 (删除我的错误答案)。我不认为有一个属性可以用来实现这一目标。我猜,但要么在点击时替换 BottomNavigationBar,要么编写您自己的版本。

标签: flutter


【解决方案1】:

您可以声明一个列表,其中包含您想要的所有图标颜色。然后将 selectedItemColor 更改为 List 的颜色。

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int currentIndex = 0;

  static const List<Color> colors = [Colors.blue, Colors.red, Colors.green];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(icon: Icon(Icons.book), label: 'Book'),
          BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings'),
        ],
        currentIndex: currentIndex,
        onTap: (value) => setState(() => currentIndex = value),
        selectedItemColor: colors[currentIndex],
      ),
    );
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多