Flutter 根界面退出的时候(即是应用退出),不会触发deactivate/dispose方法 / 监听返回按钮
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { print('----------------!!!!!build 111!!!!----------------'); return Scaffold( body: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { Navigator.of(context).push(new MaterialPageRoute(builder: (_) => SecondPage())); }, child: Container( color: Colors.red, ), )); } @override void deactivate() { super.deactivate(); print('----------------!!!!!deactivate 111!!!!----------------'); } @override void dispose() { print('----------------!!!!!dispose 111!!!!----------------'); super.dispose(); } }
输出结果:
I/flutter (18058): ----------------!!!!!build 111!!!!----------------
处理方法:使用 WillPopScope 来处理。以下是参考案例:
class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { Future<bool> _onBackPressed() { return showDialog( context: context, builder: (context) => AlertDialog( title: Text('确定退出程序吗?'), actions: <Widget>[ FlatButton( child: Text('暂不'), onPressed: () => Navigator.pop(context, false), ), FlatButton( child: Text('确定'), onPressed: () => Navigator.pop(context, true), ), ], )); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: _onBackPressed, child: Scaffold( appBar: AppBar( title: Text('title'), ), body: Center( child: Text('exit'), ), ), ); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步