Flutter Drawer功能异常:点击按钮及链接报错跳转问题
Drawer组件交互错误排查与修复
问题现象
- 点击Drawer唤起按钮时出现多种错误
- 点击Drawer内的链接时,页面卡住并弹出错误提示,随后跳转到错误页面
报错截图

对应MainDrawer组件代码
class MainDrawer extends StatelessWidget { const MainDrawer({super.key}); Widget buildListTitle(String title, IconData icon, Function function) { return ListTile( leading: Icon( icon, size: 20, ), title: Text( title, style: TextStyle( fontFamily: 'RobotoCondensed', fontSize: 24, fontWeight: FontWeight.bold), ), onTap: function(), ); } @override Widget build(BuildContext context) { return Drawer( child: Column( children: [ Container( height: 120, width: double.infinity, padding: EdgeInsets.all(20), alignment: Alignment.centerLeft, color: Theme.of(context).accentColor, child: Text( 'cooking up', style: TextStyle( fontWeight: FontWeight.w900, fontSize: 30, color: Theme.of(context).primaryColor, ), ), ), SizedBox( height: 20, ), buildListTitle("Meal", Icons.restaurant, () { Navigator.of(context).pushNamed("/"); }), buildListTitle("Meal", Icons.restaurant, () { Navigator.of(context).pushNamed(FilterScreen.routeName); }), ], ), ); } }
问题根源与修复
错误核心在于buildListTitle方法中,onTap属性被赋值为function()——这会立即执行传入的函数,而非将函数作为回调绑定。组件构建阶段就触发Navigator操作,直接导致上下文异常、路由错误等一系列问题。
修复步骤
- 将
buildListTitle的参数类型从Function改为VoidCallback,符合Flutter回调规范 - 将
onTap: function()改为onTap: function,传递函数引用而非执行结果 - 优化:将第二个列表项标题改为"Filters",避免重复造成混淆
修复后的代码
class MainDrawer extends StatelessWidget { const MainDrawer({super.key}); Widget buildListTitle(String title, IconData icon, VoidCallback function) { return ListTile( leading: Icon( icon, size: 20, ), title: Text( title, style: TextStyle( fontFamily: 'RobotoCondensed', fontSize: 24, fontWeight: FontWeight.bold), ), onTap: function, ); } @override Widget build(BuildContext context) { return Drawer( child: Column( children: [ Container( height: 120, width: double.infinity, padding: EdgeInsets.all(20), alignment: Alignment.centerLeft, color: Theme.of(context).accentColor, child: Text( 'cooking up', style: TextStyle( fontWeight: FontWeight.w900, fontSize: 30, color: Theme.of(context).primaryColor, ), ), ), SizedBox( height: 20, ), buildListTitle("Meal", Icons.restaurant, () { Navigator.of(context).pushNamed("/"); }), buildListTitle("Filters", Icons.settings, () { Navigator.of(context).pushNamed(FilterScreen.routeName); }), ], ), ); } }
补充说明
绑定function()时,组件构建阶段就会执行导航逻辑,此时Drawer尚未完全初始化,上下文状态异常,进而引发路由跳转报错;使用VoidCallback可提升代码类型安全性,避免非空等潜在问题。
内容的提问来源于stack exchange,提问作者M.Shahzad
相关产品推荐
相关产品推荐

