1// Copyright 2016 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5import 'package:flutter/widgets.dart'; 6 7class LifecycleWatcher extends StatefulWidget { 8 const LifecycleWatcher({ Key key }) : super(key: key); 9 10 @override 11 _LifecycleWatcherState createState() => _LifecycleWatcherState(); 12} 13 14class _LifecycleWatcherState extends State<LifecycleWatcher> 15 with WidgetsBindingObserver { 16 AppLifecycleState _lastLifecycleState; 17 18 @override 19 void initState() { 20 super.initState(); 21 WidgetsBinding.instance.addObserver(this); 22 } 23 24 @override 25 void dispose() { 26 WidgetsBinding.instance.removeObserver(this); 27 super.dispose(); 28 } 29 30 @override 31 void didChangeAppLifecycleState(AppLifecycleState state) { 32 setState(() { 33 _lastLifecycleState = state; 34 }); 35 } 36 37 @override 38 Widget build(BuildContext context) { 39 if (_lastLifecycleState == null) 40 return const Text('This widget has not observed any lifecycle changes.'); 41 return Text('The most recent lifecycle state this widget observed was: $_lastLifecycleState.'); 42 } 43} 44 45 46void main() { 47 runApp( 48 const Directionality( 49 textDirection: TextDirection.ltr, 50 child: Center( 51 child: LifecycleWatcher(), 52 ), 53 ), 54 ); 55} 56