禁止返回其实用到的地方也是比较多的,例如三秒广告,登录界面等等,
点击按钮跳转页面无法返回到上一个页面,其实也就是在跳转的同时将上一个栈给删掉了或者说替换称为空的了:
老样子还是先上整体的代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: MyApp1(),
),
);
}
}
class MyApp1 extends StatefulWidget {
const MyApp1({Key? key}) : super(key: key);
@override
State<MyApp1> createState() => _MyApp1State();
}
class _MyApp1State extends State<MyApp1> {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Center(
child: Container(
width: size.width,
height: size.height,
color: Colors.red[100],
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: () {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (builder) {
return MyApp2();
}), (route) => route == null);
},
)
],
),
),
);
}
}
class MyApp2 extends StatelessWidget {
const MyApp2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Column(
children: [
Container(
width: size.width,
height: size.height,
color: Colors.blue[100],
)
],
);
}
}
主要的代码:
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (builder) {
return MyApp2();
}), (route) => route == null);
pushAndRemoveUntil 将给定路由推送到Navigator,删除先前的路由,直到该函数的参数predicate返回true为止