メインコンテンツへスキップ
見出し画像

アイコンホバー時(あるいは選択時)に中身の詰まったアイコンに切り替える実装

    「アイコンホバー時(あるいは選択時)に中身の詰まったアイコンに切り替える」というのは、Material Design 3などでも推奨されている、現在の標準的なUIデザインパターンですね。ユーザーに「今どこにいるか」や「押せること」を直感的に伝えるのに非常に効果的です。

    実装方法は大きく分けて2つのパターンがあります。目的に合わせて選んでください。

    1. 【推奨】タブを選択した時に切り替える (activeIcon を使う)

      • スマホアプリやYouTubeのボトムナビのような標準的な挙動です。

      • 「選択されているタブ」が塗りつぶされ、「選択されていないタブ」がアウトラインになります。

    2. 【Web/Desktop向け】マウスカーソルが乗った瞬間に切り替える (MouseRegion を使う)

      • マウス操作特有の「ホバー」挙動です。クリックする前に見た目が変わります。

    一般的に「押した感じ(選択状態)」を出したい場合は パターン1 が正解です。今回はこのパターン1を中心に、具体的なコード修正箇所を解説します。


    修正前のソースコード

    import 'package:flutter/material.dart';
    import 'package:study_tree/01_Pages/01_Repository/RepositoryListPage.dart';
    import 'package:study_tree/01_Pages/04_Setting/SettingsPage.dart';
    import 'package:study_tree/01_Pages/06_YoutubeLikeBottomNavigationBar/NavigationBarColor.dart';
    
    // なるほど — 見た目が黒くなるのはよくあるハマりで、原因はだいたいこのどれか:
    // BottomNavigationBar を包む Material(内部的に使われるもの)が デフォルトで暗い色を描画している
    // Scaffold がボトム領域を覆っていて 透過が効いていない(extendBody が無い)
    // Material3 の surfaceTintColor / テーマが干渉して、透明にしても暗めのオーバーレイが乗る
    
    // ▼ user-defined(自分で定義する StatefulWidget)
    class YoutubeLikeBottomNavigationBar extends StatefulWidget {
      const YoutubeLikeBottomNavigationBar({super.key});
    
      @override
      State<YoutubeLikeBottomNavigationBar> createState() => _YoutubeLikeBottomNavigationBarState();
    }
    
    // ▼ user-defined(自分の State クラス)
    class _YoutubeLikeBottomNavigationBarState extends State<YoutubeLikeBottomNavigationBar> {
      // ▼ user-defined: 今選ばれてるタブ index
      int selectedTabIndex = 0;
    
      // ▼ user-defined: 各タブ用の NavigatorState を外部から操作するための GlobalKey
      final List<GlobalKey<NavigatorState>> navigatorKeys = List.generate(
        2, // タブ数(必要なら増やす)
        (_) => GlobalKey<NavigatorState>(),
      );
    
      @override
      Widget build(BuildContext context) {
        //------------------------------------------------------------------
        final navigationBarBackGroundColor = NavigationBarColor.getNavigationBarBackGroundColor(context);
        final unselectedItemColor = NavigationBarColor.getUnselectedItemColor(context);
        //------------------------------------------------------------------
        return Container(
          // outer background(user-defined): 画面全体に薄い白を重ねる例
          decoration: const BoxDecoration(
            color: Color.fromARGB(34, 255, 255, 255),
          ),
          child: Scaffold(
            // ★ 重要: extendBody を true にして、body が bottomNavigationBar の背後まで伸びるようにする
            extendBody: true,
    
            // 既にやってるけど念押し:Scaffold の背景は透明にしておく
            backgroundColor: Colors.transparent,
    
            body: IndexedStack(
              index: selectedTabIndex,
              children: [
                _buildTabNavigator(0, const RepositoryListPage()),
                _buildTabNavigator(1, const SettingsPage()),
              ],
            ),
    
            // ★ BottomNavigationBar を Material でラップして内部 Material の色/影を潰す
            bottomNavigationBar: Material(
              color: navigationBarBackGroundColor, // Material自体の色を透明に(これが効かないと黒っぽさが残る)
              // color: const Color.fromARGB(0, 255, 255, 255),
              elevation: 0, // Material の影を消す(念のため)BottomNavigationBar を包む Material(内部的に使われるもの)が デフォルトで暗い色を描画している
              child: BottomNavigationBar(
                // バー自体も透明に
                backgroundColor: Colors.transparent,
                elevation: 0, // アイコンの下の影を消す
                type: BottomNavigationBarType
                    .fixed, // アイテムがシフトして見た目が変わるのを抑える(安定)
                selectedItemColor: const Color.fromARGB(255, 255, 191, 0),
                unselectedItemColor: unselectedItemColor,
                currentIndex: selectedTabIndex,
                onTap: _onTapBottomNavItem,
                items: const [
                  BottomNavigationBarItem(
                    icon: Icon(Icons.folder_outlined), // 未選択時: アウトライン
                    activeIcon: Icon(Icons.folder),    // 選択時: 塗りつぶし (Filled)
                    label: "リポジトリ"
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.settings_outlined), // 未選択時: アウトライン
                    activeIcon: Icon(Icons.settings), // 選択時: 塗りつぶし (Filled)
                    label: "設定"
                  ),
                ],
              ),
            ),
          ),
        );
      }
    
      Widget _buildTabNavigator(int tabIndex, Widget rootPage) {
        return Navigator(
          key: navigatorKeys[tabIndex],
          onGenerateRoute: (settings) => MaterialPageRoute(
            builder: (_) => rootPage,
          ),
        );
      }
    
      void _onTapBottomNavItem(int tappedTabIndex) {
        if (tappedTabIndex == selectedTabIndex) {
          final navState = navigatorKeys[tappedTabIndex].currentState;
          if (navState != null) {
            navState.popUntil((route) => route.isFirst);
          }
        } else {
          setState(() {
            selectedTabIndex = tappedTabIndex;
          });
        }
      }
    }
    

    実装方法:activeIcon を設定する

    BottomNavigationBarItem には icon(通常時)とは別に、activeIcon(選択時)というプロパティがあります。ここに「中身の詰まったアイコン」を指定するだけで実装できます。

    下記が修正後のコードです。

    (※変更点は items プロパティの中身のみです)

    Dart

    // ... (前略)
    
            // ★ BottomNavigationBar を Material でラップして内部 Material の色/影を潰す
            bottomNavigationBar: Material(
              color: navigationBarBackGroundColor, 
              elevation: 0, 
              child: BottomNavigationBar(
                // バー自体も透明に
                backgroundColor: Colors.transparent,
                elevation: 0, 
                type: BottomNavigationBarType.fixed, 
                selectedItemColor: const Color.fromARGB(255, 255, 191, 0),
                unselectedItemColor: unselectedItemColor,
                currentIndex: selectedTabIndex,
                onTap: _onTapBottomNavItem,
                
                // ▼▼▼ 修正箇所はここだけです ▼▼▼
                items: const [
                  BottomNavigationBarItem(
                    icon: Icon(Icons.folder_outlined), // 未選択時: アウトライン
                    activeIcon: Icon(Icons.folder),    // 選択時: 塗りつぶし (Filled)
                    label: "リポジトリ",
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.settings_outlined), // 未選択時: アウトライン
                    activeIcon: Icon(Icons.settings),    // 選択時: 塗りつぶし (Filled)
                    label: "設定",
                  ),
                ],
                // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
                
              ),
            ),
          ),
        );
      }
    // ... (後略)
    

    解説

    • icon: 非選択状態(currentIndex と一致しない時)に表示されるウィジェットです。ここでは _outlined 系を指定します。

    • activeIcon: 選択状態(currentIndex と一致する時)に表示されるウィジェットです。ここに通常(Filled)のアイコンを指定することで、タブを切り替えた瞬間にアイコンが「カチッ」と塗りつぶされた状態に変化し、押した実感が湧きます。


    【補足】もし本当に「マウスホバー(クリック前)」で切り替えたい場合

    もしFlutter Webなどで「クリックしなくても、マウスを乗せただけでアイコンを切り替えたい」場合は、標準機能にはないため、自作のウィジェットを作る必要があります。

    その場合は、以下のような HoverIcon クラスを作成し、BottomNavigationBarItem の icon に指定します。

    Dart

    // ホバー検知用のウィジェット定義
    class HoverIcon extends StatefulWidget {
      final IconData icon;       // 通常時のアイコン
      final IconData hoveredIcon;// ホバー時のアイコン
    
      const HoverIcon({
        super.key,
        required this.icon,
        required this.hoveredIcon,
      });
    
      @override
      State<HoverIcon> createState() => _HoverIconState();
    }
    
    class _HoverIconState extends State<HoverIcon> {
      bool isHovered = false;
    
      @override
      Widget build(BuildContext context) {
        // IconTheme.of(context) を使うことで、BottomNavigationBarの色設定を引き継げます
        final iconColor = IconTheme.of(context).color;
    
        return MouseRegion(
          onEnter: (_) => setState(() => isHovered = true),
          onExit: (_) => setState(() => isHovered = false),
          child: Icon(
            isHovered ? widget.hoveredIcon : widget.icon,
            color: iconColor,
          ),
        );
      }
    }
    

    使い方:

    Dart

    BottomNavigationBarItem(
      // マウスホバーで切り替わる自作ウィジェットを指定
      icon: HoverIcon(
        icon: Icons.folder_outlined,
        hoveredIcon: Icons.folder,
      ),
      activeIcon: Icon(Icons.folder), // 選択後は常に塗りつぶし
      label: "リポジトリ",
    ),
    

    次のアクション

    まずは activeIcon プロパティを追加する方法 を試してみてください。これだけでアプリの品質(触り心地)がグッと上がります。

    あなたへのおすすめ