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
相关产品推荐
相关产品推荐

