1

I am using Flutter with hooks and I am trying to get the App Life Cycle State. I followed documentation and created new hook (code shown below) which works ok for all situations with one exception. When the application state becomes "paused", the hook does not return the value back to the widget. I am not clear what to do at this point. Someone suggested using Isolates but I don't see how that can help. Updating App Life Cycle is not compute expensive.

Please let me know what else I could do make this work. Thanks

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

AppLifecycleState useAppLifecycleState() {
  return use(const _LifeCycleState());
}

class _LifeCycleState extends Hook<AppLifecycleState> {
  const _LifeCycleState();

  @override
  __LifeCycleState createState() => __LifeCycleState();
}

class __LifeCycleState extends HookState<AppLifecycleState, _LifeCycleState>
    with WidgetsBindingObserver {
  AppLifecycleState _state;

  @override
  void initHook() {
    super.initHook();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  AppLifecycleState build(BuildContext context) {
    return _state;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _state = state;
    });
    super.didChangeAppLifecycleState(state);
  }
}

Thanks for your help.

Aimn Blbol
  • 907
  • 11
  • 20
  • Are you still running an isolate that's not tied to the UI? If not, you are inactive... that's probably what you're getting. In your background isolate, you would probably see detached. Hard to run any code otherwise. :) – Randal Schwartz Mar 01 '21 at 18:26
  • I am not running any isolate in my code!!. Do I need to run above code in an isolate? Please explain a bit more as I am still learning Dart and Flutter. Thanks for your help. – Aimn Blbol Mar 01 '21 at 20:27
  • Well, you're running the UI Isolate, always, except when you're not the topmost app. Background is possible... see https://flutter.dev/docs/development/packages-and-plugins/background-processes – Randal Schwartz Mar 01 '21 at 20:37

0 Answers0