我想在抽屉打开时隐藏一些小部件。 (这意味着当用户打开抽屉时,我需要隐藏一些小部件)
目前,我正在使用
if(!_scaffoldKey.currentState.isDrawerOpen)
//hide widget
但这不是
listen
。有什么方法可以监听抽屉回调吗? 最佳答案
到目前为止,在flutter中还没有回调函数可以为Drawer()
提供事件,但是我们仍然可以为其应用一个好的解决方案。
我使用两个有状态的小部件划分了解决方案,
1.主屏幕:
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
bool _isDrawerOpen = false;
void drawerCallback(bool isOpen) {
print('Drawer Status:' + isOpen.toString());
// Based on the bool value set visibility of your widget
WidgetsBinding.instance.addPostFrameCallback((_){
setState(() {
_isDrawerOpen = isOpen;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(title: Text('Nav Sample App')),
body: _isDrawerOpen
? Align(alignment: Alignment.centerRight, child: Text('Drawer Open'))
: Align(alignment: Alignment.centerRight, child: Text('Drawr Close')),
drawer: MyDrawer(drawerCallback));
}
}
在上面可以看到,基于
_isDrawerOpen
,我们在主体中使用三元运算符设置了小部件。2. MyDrawer()
class MyDrawer extends StatefulWidget {
final Function _drawerCallback;
MyDrawer(this._drawerCallback);
@override
_MyDrawerState createState() => _MyDrawerState();
}
class _MyDrawerState extends State<MyDrawer> {
@override
void initState() {
super.initState();
widget._drawerCallback(true);
}
@override
void dispose() {
widget._drawerCallback(false);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(color: Colors.blue),
),
Text("Drawer Item 1"),
Text("Drawer Item 2"),
],
),
);
}
}
逻辑的核心应用在我们返回状态的
initState()
和dispose()
回调中。