如果您创建Scafold,则可以选择抽屉.如果您现在创建此抽屉,则会自动获得应用栏前导位置上的菜单图标.但我想在那里打开抽屉的另一个图标.我尝试在领先位置自己制作一个iconbutton但是这个按钮无法打开抽屉,即使是"Scafold.of(context).openDrawer()"也无法打开它.
是否有任何选项可以替换抽屉按钮的图标?
azi*_*iza 56
使用Key你的,Scaffold并通过调用显示抽屉myKey.currentState.openDrawer(),这是一个工作代码:
import "package:flutter/material.dart";
class Test extends StatefulWidget {
@override
_TestState createState() => new _TestState();
}
class _TestState extends State<Test> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
drawer: new Drawer(),
appBar: new AppBar(
leading: new IconButton(icon: new Icon(Icons.settings),
onPressed: () => _scaffoldKey.currentState.openDrawer()),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
Seb*_*oth 26
替代接受的答案,不需要GlobalKey:
class _TestState extends State<Test> {
@override
Widget build(BuildContext context) {
return new Scaffold(
drawer: new Drawer(),
appBar: new AppBar(
leading: Builder(
builder: (context) => IconButton(
icon: new Icon(Icons.settings),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 13
使用全局密钥:
final GlobalKey<ScaffoldState> _key = GlobalKey(); // Create a key
@override
Widget build(BuildContext context) {
return Scaffold(
key: _key, // Assign the key to Scaffold.
drawer: Drawer(),
floatingActionButton: FloatingActionButton(
onPressed: () => _key.currentState!.openDrawer(), // <-- Opens drawer
),
);
}
Run Code Online (Sandbox Code Playgroud)
使用生成器:
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
floatingActionButton: Builder(builder: (context) {
return FloatingActionButton(
onPressed: () => Scaffold.of(context).openDrawer(), // <-- Opens drawer.
);
}),
);
}
Run Code Online (Sandbox Code Playgroud)
之后你需要初始化scaffoldKey
,
打开抽屉和关闭抽屉
GestureDetector(
onTap: () {
if(scaffoldKey.currentState.isDrawerOpen){
scaffoldKey.currentState.openEndDrawer();
}else{
scaffoldKey.currentState.openDrawer();
}
},
child: LeadingIcon(icon: Icons.menu),//your button
),
Run Code Online (Sandbox Code Playgroud)