场景:用户在首页点击按钮跳转到详情页,然后点击详情页 左上角的按钮返回时候 对其进行拦截.
方法一:在Scaffold下面用leading 属性覆盖;
方法二:在Scaffold外层用WillPopScope进行包裹;
main.dart
import 'package:flutter/material.dart';
import 'a.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue, splashColor: Colors.transparent),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String _message="首页默认显示";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("首页"),
),
body: Center(
child: Column(
children: [
ElevatedButton (
onPressed:()=>_jumpToDetail(context),
child: Text("跳转到详情"),
),
Text(_message)
],
),
)
);
}
_jumpToDetail(BuildContext context){
final res= Navigator.of(context).push(MaterialPageRoute(builder:(ctx){
return DetailPage("home 页面的值");
}));
res.then((value) => {
setState(() {
_message=value??"";
})
});
}
}
a.dart
import 'package:flutter/material.dart';
class DetailPage extends StatelessWidget {
final String _message;
DetailPage(this._message);
@override
Widget build(BuildContext context) {
return WillPopScope(
//方法二 在Scaffold外层包裹一层WillPopScope
// 当返回为true时,可以自动返回(flutter帮助我们执行返回操作)
// 当返回为false时, 自行写返回代码
onWillPop: () {
_backToHome(context);
return Future.value(false);
},
child: Scaffold(
appBar: AppBar(
title: Text("详情页"),
// 方法一:
// leading: IconButton(
// icon: Icon(Icons.backpack),
// onPressed: () => _backToHome(context),
// ),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_message, style: TextStyle(fontSize: 20),),
ElevatedButton (
child: Text("回到首页"),
onPressed: () => _backToHome(context),
)
],
),
),
),
);
}
void _backToHome(BuildContext context) {
Navigator.of(context).pop("a detail message");
}
}