Flutter如何在拆分后的自定义AppBar组件内调用Scaffold的key打开抽屉
解决方案
方法1:传入回调函数(最推荐,低耦合)
- 第一步:给自定义AppBar组件添加
onOpenDrawer回调参数
class AppBar extends StatefulWidget { const AppBar({ required this.deviceConnector, // 新增回调参数 required this.onOpenDrawer, Key? key, }) : super(key: key); final VoidCallback onOpenDrawer; final dynamic deviceConnector; // 原有参数保留即可 @override State<AppBar> createState() => _AppBarState(); }
- 第二步:在AppBar的按钮点击事件中调用回调
ElevatedButton( child: Icon( Icons.settings, size: 38, color: Colors.white, ), onPressed: () => widget.onOpenDrawer(), )
- 第三步:在父页面使用AppBar时传入打开抽屉的逻辑
class _Page1State extends State<_Page1> { final GlobalKey<ScaffoldState> _key = GlobalKey(); Widget build(BuildContext context) => Scaffold( key: _key, appBar: AppBar( deviceConnector: yourDeviceConnector, // 传入打开抽屉的逻辑 onOpenDrawer: () => _key.currentState?.openDrawer(), ), body: Container(), // 原有drawer配置保留即可 ); }
方法2:直接从Context获取ScaffoldState(无需额外传参)
AppBar组件属于Scaffold的子节点,直接用Scaffold.of即可拿到当前Scaffold的状态:
ElevatedButton( child: Icon( Icons.settings, size: 38, color: Colors.white, ), onPressed: () => Scaffold.of(context).openDrawer(), )
如果遇到Scaffold.of找不到的情况,给按钮套一层Builder组件获取子context即可解决。
方法3:传入Scaffold的GlobalKey(不推荐,耦合度高)
给自定义AppBar加接收GlobalKey的参数,父页面把Scaffold的_key传入AppBar,在AppBar内直接调用key.currentState?.openDrawer()即可,这种方式会让AppBar组件和父页面强绑定,复用性差。
内容的提问来源于stack exchange,提问作者vontdeux
相关产品推荐
相关产品推荐

