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(); } }

輸出結果:app

I/flutter (18058): ----------------!!!!!build  111!!!!----------------

處理方法:使用 WillPopScope 來處理。如下是參考案例:less

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'), ), ), ); } }
相關文章
相關標籤/搜索