当我按照 Add a Drawer to a screen docs 创建抽屉布局时,它工作正常。但是,我有一个问题,这是菜单图标。
在 Android 中,我使用 DrawerToggle 设置抽屉布局,当我打开抽屉时,菜单图标将变为箭头图标,当我关闭抽屉时,箭头图标将变为菜单图标。
在 Flutter 中,它不像上面那样工作。
如果你明白我的问题,请帮助我。我搜索了很多,但没有找到解决方案。所以想问问大家。非常感谢。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final appTitle = 'Drawer Demo';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(child: Text('My Page!')),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the Drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Item 1'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: Text('Item 2'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
],
),
),
);
}
}
最佳答案
使用StateFulWidget
,这样您就可以访问setState
方法来更改图标
在您的状态
类中
定义一个全局键
final GlobalKey<ScaffoldState> _key = GlobalKey();
定义一个boolean
来检查Drawer
是否打开。
bool _isDrawerOpen = false;
将这些添加到您的状态
类
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Title'),
leading: IconButton(
icon: _isDrawerOpen ? Icon(Icons.menu) : Icon(Icons.arrow_back),
onPressed: onPressed,
),
),
drawer: WillPopScope(child: Drawer(), onWillPop: onPop),
body: //body
key: this._key,
);
}
void onPressed() {
if (!_isDrawerOpen) {
this._key.currentState.openDrawer();
} else {
Navigator.pop(context);
}
setState(() {
_isDrawerOpen = !_isDrawerOpen;
});
}
void onPop() {
if (_isDrawerOpen) {
setState(() {
_isDrawerOpen = false;
});
}
Navigator.pop(context);
}
关于flutter - 打开/关闭抽屉布局时如何将抽屉导航汉堡菜单图标更改为箭头图标 - Flutter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55841706/