原因:
在 Flutter 中,Scaffold.of(context)
会沿着当前的 context
向上查找最近的 Scaffold
。如果当前的 widget 树层级中没有合适的 Scaffold
(比如按钮所在的 context 是在某个子 widget 中),就找不到它。
解决办法:
1.你可以使用 Builder
来创建一个新的 context
,这个新的 context 是属于 Scaffold
的子树,这样就能正确找到 Scaffold
。
dart
class RightDrawerExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
endDrawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('右侧抽屉'),
),
ListTile(
title: Text('选项 1'),
onTap: () {
Navigator.pop(context); // 关闭抽屉
},
),
ListTile(
title: Text('选项 2'),
onTap: () {
Navigator.pop(context); // 关闭抽屉
},
),
],
),
),
body: Center(
child: Builder(
builder: (context) => ElevatedButton(
onPressed: () {
Scaffold.of(context).openEndDrawer();
},
child: Text('打开右侧抽屉'),
),
),
),
);
}
}
2.也可以通过 GlobalKey 来访问 Scaffold
dart
class RightDrawerExample extends StatefulWidget {
@override
_RightDrawerExampleState createState() => _RightDrawerExampleState();
}
class _RightDrawerExampleState extends State<RightDrawerExample> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey, // 设置 key
endDrawer: Drawer(
child: Center(child: Text('这是一个从右侧滑出的抽屉')),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_scaffoldKey.currentState?.openEndDrawer(); // 使用 key 打开抽屉
},
child: Text('打开右侧抽屉'),
),
),
);
}
}