Search code examples
flutterandroid-livedata

What is the equivalent of Android LiveData in Flutter?


Android's LiveData allows to update the UI when the activity is in an active state. So if a background operation has finished while the activity is paused, the activity won't be notified and thus the app won't crush. Can Flutter perform the same behavior?


Solution

  • You can use WidgetsBindingObserver to listen to the application state.

    class AppLifecycleReactor extends StatefulWidget {
      const AppLifecycleReactor({ Key key }) : super(key: key);
    
      @override
      _AppLifecycleReactorState createState() => new _AppLifecycleReactorState();
    }
    
    class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    
      AppLifecycleState _notification;
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        setState(() { _notification = state; });
      }
    
      @override
      Widget build(BuildContext context) {
        return new Text('Last notification: $_notification');
      }
    }