3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】Flutter HooksでdidChangeAppLifecycleStateのタイミングで通知する

Posted at

はじめに

HookWidgetを利用していて、画面が復帰したときに再描画したい場合があり、CustomHooksを書いて見ました。
https://pub.dev/packages/flutter_hooks/changelog#0181
にてすでに実装されていましたが、今回はCustom Fookを作って見たくて、実装して見ました。

動作環境

flutterSdkVersion": "2.5.3"
flutter_hooks: ^0.17.0

コード

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

AppLifecycleState? useAppLifecycleState(AppLifecycleState notifyState) {
  return use(_LifeCycleState(notifyState));
}

class _LifeCycleState extends Hook<AppLifecycleState?> {
  const _LifeCycleState(this.notifyState);
  final AppLifecycleState notifyState;
  @override
  __LifeCycleState createState() => __LifeCycleState(notifyState);
}

class __LifeCycleState extends HookState<AppLifecycleState?, _LifeCycleState>
    with WidgetsBindingObserver {
  __LifeCycleState(this.notifyState);
  AppLifecycleState? _theState;
  AppLifecycleState notifyState;
  @override
  void initHook() {
    super.initHook();
    WidgetsBinding.instance!.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (notifyState == state) {
      setState(() {
        _theState = state;
      });
    }
  }

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

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

class HookWidget extends HookWidget {
  HookWidget({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
     //resumeの時だけ通知する
     useAppLifecycleState(AppLifecycleState.resumed);
     return Container();
  }

最後に

以下のrepositoryにも超便利なhooksが揃っていたりするので、利用したほうが
開発効率が上がりそうですね!
https://github.com/wasabeef/flutter_use

今回は自分でCustom Hookを作ってみました
アドバイスなどありましたら、是非よろしくお願いいたします!!

3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?