【发布时间】:2019-06-01 12:46:34
【问题描述】:
我创建了一个 AppDrawer 小部件来包装我的主抽屉导航并在一个地方引用它,如下所示:
class AppDrawer extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Drawer(
child: new ListView(
children: <Widget>[
new ListTile(
title: new Text("Page1"),
trailing: new Icon(Icons.arrow_right),
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => Page1.singleInstance));
}
),
new ListTile(
title: new Text("Page2"),
trailing: new Icon(Icons.arrow_right),
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new Page2("Page 2")));
}
),
]
),
);
}
}
我还创建了一个自定义 AppScaffold 小部件,它只返回一个一致的 AppBar、我的自定义 AppDrawer 和正文:
class AppScaffold extends StatelessWidget {
final Widget body;
final String pageTitle;
AppScaffold({this.body, this.pageTitle});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(title: new Text(pageTitle), backgroundColor: jet),
drawer: AppDrawer(),
body: body
);
}
}
我创建了两个页面:Page1 和 Page2。它们现在很简单,看起来像这样:
class Page1 extends StatelessWidget {
final String pageText;
Page1(this.pageText);
static Page1 get singleInstance => Page1("Page1");
Widget build(BuildContext context) {
return AppScaffold(
pageTitle: this.pageText,
body: SafeArea(
child: Stack(
children: <Widget>[
Center(child: SomeCustomWidget())
],
)
),
);
}
}
class Page2 extends StatelessWidget {
final String pageText;
Page2(this.pageText);
@override
Widget build(BuildContext context) {
return AppScaffold(
pageTitle: this.pageText,
body: SafeArea(
child: Stack(
children: <Widget>[
Center(child: SomeOtherCustomWidget())
],
)
),
);
}
}
当我运行我的应用程序时,我可以正确地看到导航栏和抽屉。我可以单击抽屉中的链接在我的页面之间导航。但是,每次我导航到一个页面时,该页面上的所有小部件都会重置为其初始状态。我想确保小部件不会被重置。另一种思考方式是:我只希望在应用程序的整个生命周期中每个页面都有一个实例,而不是在用户导航到它们时创建新的实例。
我尝试创建一个 Page1 的静态实例,当触发 onTap 事件时 Drawer 使用该实例,但这不起作用。我想错了吗?我需要转换为有状态小部件吗?
【问题讨论】:
标签: flutter