You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用google_nav_bar实现点击底部导航标签切换对应页面类

解决方案

你的代码核心切换逻辑本身已符合要求,若未正常实现点击切换效果,可按以下步骤排查修正:

  • 确认pubspec.yaml中已正确添加依赖,且执行过flutter pub get命令:
dependencies:
  flutter:
    sdk: flutter
  google_nav_bar: ^最新稳定版本号
  line_icons: ^最新稳定版本号
  • 检查Home、Likes、Profile三个类均为合法的Flutter Widget,返回了正常的页面布局内容,而非空组件。
  • 移除body外层多余的Center组件,你当前用Center包裹页面会导致页面内容按子组件大小居中展示,无法占满全屏,修正后body直接使用页面列表取值即可。

修正后完整可运行代码

import 'package:flutter/material.dart';
import 'package:google_nav_bar/google_nav_bar.dart';
import 'package:line_icons/line_icons.dart';

// 示例页面定义,你可替换为自己的页面实现
class Home extends StatelessWidget {
  const Home({super.key});
  @override
  Widget build(BuildContext context) {
    return const Scaffold(body: Center(child: Text("首页内容")));
  }
}
class Likes extends StatelessWidget {
  const Likes({super.key});
  @override
  Widget build(BuildContext context) {
    return const Scaffold(body: Center(child: Text("喜欢页内容")));
  }
}
class Profile extends StatelessWidget {
  const Profile({super.key});
  @override
  Widget build(BuildContext context) {
    return const Scaffold(body: Center(child: Text("个人页内容")));
  }
}

class MainScreen extends StatefulWidget {
  const MainScreen({super.key});
  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  int _currentIndex = 0;

  final List<Widget> _screens = const [
    Home(),
    Likes(),
    Profile(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      bottomNavigationBar: GNav(
        rippleColor: Colors.grey[300]!,
        hoverColor: Colors.grey[100]!,
        gap: 8,
        activeColor: Colors.black,
        iconSize: 24,
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        duration: const Duration(milliseconds: 400),
        tabBackgroundColor: Colors.grey[100]!,
        color: Colors.black,
        tabs: const [
          GButton(
            icon: LineIcons.home,
            text: 'Home',
          ),
          GButton(
            icon: LineIcons.heart,
            text: 'Likes',
          ),
          GButton(
            icon: LineIcons.user,
            text: 'Profile',
          ),
        ],
        selectedIndex: _currentIndex,
        onTabChange: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
      // 若需要保留页面状态(切换时不重建页面、保留滚动位置/输入内容),可替换为下方注释的IndexedStack实现
      // body: IndexedStack(
      //   index: _currentIndex,
      //   children: _screens,
      // ),
      body: _screens[_currentIndex],
    );
  }
}

内容的提问来源于stack exchange,提问作者Lauren Tsai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:15:04