SUP*_*MAN 7 navigation alert flutter
有没有办法配置 willPopScope 来捕获自定义弹出导航,如下所示?我有一个自定义 Raisingbutton 小部件,带有 onPressed 来导航回上一页。
但 willPopScope 不会像 AppBar 后退按钮那样捕获导航。我不确定这是否可能。请指教。谢谢!
WillPopScope(
child: Scaffold(
body: Container(
child: Center(
child: RaisedButton(
onPressed:(){
return Navigator.pop(context);
},
child: Text("Go Back),
),
),
),
),
onWillPop: () async {
// code to show a modal
}
);
Run Code Online (Sandbox Code Playgroud)
Mar*_*lla 11
这是实现您的目标的完整示例。WillPopScope需要maybePop调用才能执行您的逻辑:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: RaisedButton(
child: Text('Jump To Next Screen'),
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (_) => ModalScreen())),
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class ModalScreen extends StatefulWidget {
@override
_ModalScreenState createState() => _ModalScreenState();
}
class _ModalScreenState extends State<ModalScreen> {
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(
appBar: AppBar(
leading: InkResponse(
child: Icon(Icons.arrow_back),
onTap: () => Navigator.of(context).maybePop(),
),
),
backgroundColor: Colors.blue,
body: Center(
child: RaisedButton(
child: Text('Let\'s go back'),
onPressed: () {
Navigator.of(context).maybePop();
},
),
),
),
onWillPop: () => _willPop(context),
);
}
Future<bool> _willPop(BuildContext context) {
final completer = Completer<bool>();
showModalBottomSheet(
context: context,
builder: (buildContext) {
return SizedBox(
height: 200,
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Text('Are you sure?'),
),
MaterialButton(
child: Text('YES'),
onPressed: () {
completer.complete(true);
Navigator.of(context).pop();
}),
MaterialButton(
child: Text('NO'),
onPressed: () {
completer.complete(true);
}),
],
),
);
});
return completer.future;
}
}
Run Code Online (Sandbox Code Playgroud)
返回true模态框后,您还需要弹出屏幕,因为模态框有自己的上下文需要弹出。
最终结果如下: