import 'package:flutter/cupertino.dart';

/// App前台、后台切换时回调
/// [isForeground] 是否前台
typedef OnAppLifecycleChangeCallback = void Function(bool isForeground);

/// 监听App前后台的组件
class AppLifecycleWidget extends StatefulWidget {
  /// 子组件
  final Widget child;

  final OnAppLifecycleChangeCallback? onAppLifecycleCallback;

  const AppLifecycleWidget({
    super.key,
    required this.child,
    this.onAppLifecycleCallback,
  });

  @override
  State<StatefulWidget> createState() {
    return _AppLifecycleWidgetState();
  }
}

class _AppLifecycleWidgetState extends State<AppLifecycleWidget>
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    // 添加App生命周期监听
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    // 移除App生命周期监听
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 切换到前台
    if (state == AppLifecycleState.resumed) {
      if (widget.onAppLifecycleCallback != null) {
        widget.onAppLifecycleCallback!(true);
      }
    } else if (state == AppLifecycleState.paused) {
      // 切换到后台
      if (widget.onAppLifecycleCallback != null) {
        widget.onAppLifecycleCallback!(false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
