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

Flutter使用BottomNavigationBar时如何向首页传递参数

问题解决方案
  • 首先修复循环嵌套bug
    你当前代码存在逻辑错误:CustomBottomNavigationBar作为容器承载了HomeScreen,但HomeScreen的bottomNavigationBar属性又再次引用了CustomBottomNavigationBar,会导致页面无限递归创建,触发内存溢出。
    修复方法:直接删除HomeScreen代码中build方法返回的Scaffold里的bottomNavigationBar: CustomBottomNavigationBar(widget.user),这行配置,将CustomBottomNavigationBar作为应用的根导航页面使用即可。

  • 底部导航关联页面的传参方案
    你现在的传参写法本身是正确的:CustomBottomNavigationBar本身接收了外部传入的UserModel实例,在初始化导航页数组的时候,直接通过构造方法将参数传给对应子页面即可。
    你现在写的HomeScreen(widget.user)已经完成了HomePage的参数传递,如果你其他页面也需要接收参数,只需要给对应页面加带参数的构造方法即可,示例如下:
    先给CallLog添加构造方法接收参数:

class CallLog extends StatefulWidget {
  final UserModel user;
  const CallLog(this.user, {super.key});

  @override
  State<CallLog> createState() => _CallLogState();
}

然后修改CustomBottomNavigationBar中的页面对象初始化逻辑:

late final screens = [
  HomeScreen(widget.user),
  CallLog(widget.user),
  CallLog(widget.user),
  CallLog(widget.user),
];
  • 额外的代码优化点
    你当前BottomNavigationBar的currentIndex属性写死为2,会导致点击导航栏时选中状态不会跟着切换,修改为绑定动态变量即可:
bottomNavigationBar: BottomNavigationBar(
  backgroundColor: Colors.black,
  selectedIconTheme: IconThemeData(color: Colors.blue),
  // 修改为动态选中索引
  currentIndex: _selectedIndex,
  // 剩余配置不变
  ...
)

所有修改完成后,你可以在HomeScreen的initState方法中打印widget.user.uid验证参数是否传递成功。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:15:03