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

如何实现Flutter底部导航栏项点击打开其他.dart页面?

实现Flutter底部导航栏点击跳转新页面

我来帮你搞定这个底部导航栏跳转页面的需求!其实思路很简单,核心是用状态管理维护当前选中的导航项,然后根据索引切换对应的页面。下面一步步来:

第一步:把你的Test组件改成StatefulWidget

因为需要跟踪当前选中的导航索引和切换页面,StatelessWidget没法维护状态,所以要改成Stateful:

第二步:创建对应的页面类

先为每个导航项准备好单独的页面组件(可以放在单独的.dart文件里,比如trends_page.dart、feed_page.dart等),举个简单的例子:

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

class TrendsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Text("Trends Page"));
  }
}

// feed_page.dart
class FeedPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Text("Feed Page"));
  }
}

// community_page.dart
class CommunityPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Text("Community Page"));
  }
}

第三步:修改Test组件实现页面切换逻辑

在State类里维护当前选中的索引,以及对应的页面列表,然后给BottomNavigationBar添加点击回调更新索引,最后在Scaffold的body里展示对应页面:

import 'package:flutter/material.dart';
// 导入你创建的页面文件
import 'trends_page.dart';
import 'feed_page.dart';
import 'community_page.dart';

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  // 维护当前选中的导航索引
  int _currentIndex = 0;

  // 页面列表,和导航项一一对应
  final List<Widget> _pages = [
    TrendsPage(),
    FeedPage(),
    CommunityPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // body展示当前索引对应的页面
      body: _pages[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        // 设置当前选中项的索引
        currentIndex: _currentIndex,
        // 点击导航项时更新索引
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.add),
            label: "trends", // 注意:现在推荐用label替代title,title已经废弃啦
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.location_on),
            label: "feed",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.people),
            label: "community",
          ),
        ],
      ),
    );
  }
}

补充说明

  • 为什么不用TabBarView?TabBarView更适合和顶部TabBar配合的滑动切换场景,而底部导航栏通常是点击切换,用这种索引+页面列表的方式更直接灵活。
  • 如果你需要更复杂的页面状态管理(比如保持页面状态不被销毁),可以用PageView配合AutomaticKeepAliveClientMixin,不过简单场景用上面的方法就足够啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:23:28