Flutter Getx中如何優雅的監聽APP的生命周期

全局可用:GetxService 在應用的整個生命周期內保持活躍,因此你可以在應用的任何部分訪問這個服務,并隨時獲取應用生命周期的狀態。

解耦:通過將生命周期邏輯放在 GetxService 中,你的控制器和 UI 組件不需要關心生命周期事件,從而簡化了代碼結構。

關鍵點說明:
LifecycleService 作為全局服務:

繼承自 GetxService,并實現了 WidgetsBindingObserver,可以監聽應用的生命周期變化。
init 方法用于初始化服務,并在啟動時添加生命周期觀察者。
Get.putAsync 用于初始化服務:

在 main 函數中,通過 Get.putAsync 將 LifecycleService 放入依賴管理中。這確保了服務在應用啟動時就被初始化,并且在整個應用生命周期內保持活躍。
didChangeAppLifecycleState 方法:

在這個方法中,你可以處理應用從前臺切換到后臺、從后臺恢復到前臺,以及其他生命周期狀態的變化。

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

class LifecycleService extends GetxService with WidgetsBindingObserver {
  Future<LifecycleService> init() async {
    WidgetsBinding.instance.addObserver(this); // 添加生命周期觀察者
    return this;
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this); // 移除生命周期觀察者
    super.onClose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      print("App is in background");
      // 處理應用進入后臺的邏輯
    } else if (state == AppLifecycleState.resumed) {
      print("App is in foreground");
      // 處理應用進入前臺的邏輯
    } else if (state == AppLifecycleState.inactive) {
      print("App is inactive");
      // 應用處于非活動狀態,例如接收到電話或短信時
    }
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('GetX Lifecycle Service Example'),
        ),
        body: Center(
          child: Text('Monitor App Lifecycle with GetX Service'),
        ),
      ),
    );
  }
}

void main() {
  // 初始化 LifecycleService 并啟動應用
  WidgetsFlutterBinding.ensureInitialized();
  Get.putAsync<LifecycleService>(() async => LifecycleService().init());
  runApp(MyApp());
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容