我为每个活动使用这个抽屉:
final MyDrawer _drawer = new MyDrawer();
class MyDrawer extends StatefulWidget {
@override
_MyDrawerState createState() => new _MyDrawerState();
}
class _MyDrawerState extends State<MyDrawer> {
@override
Widget build(BuildContext context) {
return new Drawer(
child: new ListView(
children: <Widget> [
new DrawerHeader(
child: new Text("Header"),
),
new ListTile(
leading: new Icon(Icons.home),
title: new Text("Home"),
onTap: () {
Navigator.popAndPushNamed(context, "/");
},
),
new ListTile(
leading: new Icon(Icons.android),
title: new Text("Another Page"),
onTap: () {
Navigator.popAndPushNamed(context, AnotherPage.routeName);
},
),new ListTile(
leading: new Icon(Icons.email),
title: new Text("Third Page"),
onTap: () {
Navigator.popAndPushNamed(context, ThirdPage.routeName);
}
)
]
),
);
}
}
每个页面都是一个有状态的小部件,它们共享同一个抽屉:
drawer: _drawer
我正在寻找一种方法,只有一个活动实例,而不是每次点击菜单项时创建一个新活动,我试过:
ThirdPage.routeName: (BuildContext context) =>
_thirdPage == null ? _thirdPage = new ThirdPage(title: "Third Page") : _thirdPage
是否可以根据当前活动调整抽屉实例?
答案 0 :(得分:0)
我想你正在尝试实现单例类,即只有一个实例的类。
Singleton类的一个例子:
class MyDrawer extends StatefulWidget{
static final MyDrawer _drawer = new MyDrawer._internal();
factory MyDrawer() {
return _drawer;
}
MyDrawer._internal();
@override
Widget build(BuildContext context){
return new Text("Drawer")
}
}
有关在dart中实现单件类的其他方法,您可以查看答案here。
希望有所帮助!