我有一个功能,可以导航到带有路线设置的新页面
void pushWithSettings(
{@required BuildContext context, @required Widget newPage}) {
Navigator.push(
context,
MaterialPageRoute(
settings: RouteSettings(
name: newPage.toString(),
),
builder: (_) => newPage));
}
我用弹出到一个特定的页面
Navigator.popUntil(context, ModalRoute.withName(Page().toString));
这在调试模式下运行良好,但在配置文件和发布模式下,它只弹出一次
上下文示例
import 'package:flutter/material.dart';
import 'package:flutter_app/main.dart';
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Center(child: Text("First Page"),),
RaisedButton(
onPressed: (){
pushWithSettings(context: context, newPage: SecondPage());
},
child: Text("Navigate to second", style: TextStyle(inherit: false)),
)
],
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Center(child: Text("Second Page"),),
RaisedButton(
onPressed: (){
pushWithSettings(context: context, newPage: ThirdPage());
},
child: Text("Navigate to third", style: TextStyle(inherit: false)),
)
],
);
}
}
class ThirdPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(child: Text("Third Page"),),
RaisedButton(
onPressed: (){
Navigator.popUntil(context, ModalRoute.withName(FirstPage().toString()));
},
child: Text("Navigate to first", style: TextStyle(inherit: false),),
)
],
);
}
}
在调试模式下,点击第三页中的按钮会导航到第一页,但在配置文件和发布模式下,单击按钮不会起任何作用。我目前正在稳定通道上运行flutter 1.17.4
第一个答案有效,但为了避免在所有可用页面中添加mixin,我使用了runtimeType
,因此
settings: RouteSettings(
name: newPage.toString(),
),
成为
settings: RouteSettings(
name: newPage.runtimeType.toString(),
),
我已经尝试过您的代码,一个FirstPage().toString()
在配置文件模式下返回"Widget",而在调试中返回"FirstPage"。
我会添加一个mixin,其中包含一个您可以使用的routeName字符串。
另外请记住,至少对于web,建议您的初始路由为"/"。
void pushWithSettings(
{@required BuildContext context, @required NamedRoute newPage}) {
Navigator.push(
context,
MaterialPageRoute(
settings: RouteSettings(
name: newPage.routeName,
),
builder: (_) => newPage));
}
mixin NamedRoute implements Widget {
String get routeName;
}
class ThirdPage extends StatelessWidget with NamedRoute {
@override
String get routeName => '/third_page';
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text("Third Page"),
),
RaisedButton(
onPressed: () {
Navigator.popUntil(context, ModalRoute.withName(FirstPage().routeName));
},
child: Text(
"Navigate to first",
style: TextStyle(inherit: false),
),
)
],
);
}
}
检查代码笔https://codepen.io/jamesblasco/pen/QWyBQOm