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

Flutter中如何在SlidingUpPanel的body区域加载底部导航栏对应页面

问题核心原因

你当前使用的Navigator.pushXX方法是全局路由跳转,会在当前整个页面栈上层插入新页面,自然无法加载到SlidingUpPanel的局部body区域。要实现需求,改用局部组件切换的逻辑即可,不需要调用路由跳转API,修改方案如下:


实现步骤

  • 在当前页面的State类中新增两个成员变量:存储当前选中导航索引的_currentIndex,以及对应导航页的组件列表
  • 修改BottomNavigationBar的onTap逻辑,删除原有的路由跳转代码,仅更新_currentIndex并触发页面重绘
  • 给BottomNavigationBar绑定currentIndex属性,保证底部导航选中态正常
  • 将SlidingUpPanel的body属性赋值为当前索引对应的页面组件

完整修改后代码示例

// 先导入你对应的页面组件
import 'home_page.dart';
import 'search_page.dart';
import 'library_page.dart';
import 'profile_page.dart';

class YourMainPageState extends State<YourMainPage> {
  final PanelController _pc = PanelController();
  bool isCollapsed = true;
  // ------------ 新增代码开始 ------------
  // 记录当前选中的导航索引
  int _currentIndex = 0;
  // 底部导航对应的页面列表,直接实例化你原来路由对应的页面组件即可
  final List<Widget> _navPages = [
    const HomePage(), // 对应你原来路由 '/' 的页面
    const SearchPage(), // 对应路由 '/search' 的页面
    const LibraryPage(), // 对应路由 '/library' 的页面
    const ProfilePage(), // 对应路由 '/profile' 的页面
  ];
  // ------------ 新增代码结束 ------------

  @override
  Widget build(BuildContext context) {
    var pageWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      body: SlidingUpPanel(
        controller: _pc,
        panelBuilder: (sc) {
          if (!isCollapsed) _pc.hide();
          return Container(
            child: Center(child: Text("Panel")),
          );
        },
        // ------------ 修改body部分 ------------
        body: _navPages[_currentIndex],
        // *可选优化:如果你需要页面切换保持状态(比如滚动位置、输入内容),改用IndexedStack代替上面的赋值
        // body: IndexedStack(
        //   index: _currentIndex,
        //   children: _navPages,
        // ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        // 绑定当前选中索引,保证底部导航选中态正常
        currentIndex: _currentIndex,
        onTap: (index) {
          // ------------ 修改onTap逻辑,删除原有路由跳转代码 ------------
          setState(() {
            _currentIndex = index;
          });
          // 如果需要切换导航时自动收起SlidingUpPanel,可额外加一行:_pc.close();
        },           
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
          BottomNavigationBarItem(icon: Icon(Icons.search), label: "搜索"),
          BottomNavigationBarItem(icon: Icon(Icons.book), label: "文库"),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
        ]   
      ),
    );
  }
}

补充说明

如果你的页面原本依赖路由传参,可以在实例化_navPages里的组件时直接把参数传入即可,不需要走路由参数传递逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:27:00