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'), ), ), ); } }