Untitled

mail@pastecode.io avatar
unknown
dart
2 years ago
1.4 kB
2
Indexable
Never
/* Flutter & Dart */
import 'package:flutter/material.dart';
import 'dart:convert';

/* External */
import 'package:appscheme/appscheme.dart';

class ListenAppSheme extends StatefulWidget {
  final Widget child;
  final void Function(String) shemeFn;

  ListenAppSheme({
    required this.child,
    required this.shemeFn,
  });

  @override
  State<ListenAppSheme> createState() => _ListenAppShemeState();
}

class _ListenAppShemeState extends State<ListenAppSheme> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
  }

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

  Future<String?> getSharedData() async {
    try {
      AppScheme appScheme = AppSchemeImpl.getInstance();

      SchemeEntity sheme = await appScheme.getLatestScheme();
      return json.encode(sheme.query);
    } catch (e) {
      return null;
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.resumed) {
      await getSharedData().then((value) {
        if (value != null) {
          handleSharedData(value);
        }
      });
    }
  }

  void handleSharedData(String? sharedData) async {
    if (sharedData != null) {
      widget.shemeFn(sharedData);
    }
  }

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