app_lifecycle

  • 原生的生命周期函数,支持 iOS 和 Android,不同于 flutter 中自带的 WidgetBindings
  • WidgetBindings 主要是指跳出 flutter UIController/Activity事件,而本插件是整个 App 级别的。
  • Android 没有激活或者取消激活状态。

demo

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<String> eventStrings = ['first null'];

  @override
  void initState() {
    super.initState();
    AppLifecycle.lifeCycleStream.listen((event) {
      print('event = $event');
      eventStrings.add("${DateTime.now()} --- ${event.shortStr}");
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: ListView.separated(
            itemCount: eventStrings.length,
            separatorBuilder: (context, index) => Container(
              height: 0.3,
              color: Colors.grey,
            ),
            itemBuilder: (context, index) {
              return Container(
                height: 30,
                child: Center(child: Text('${eventStrings[index]}')),
              );
            },
          ),
        ),
      ),
    );
  }
}

Android 使用库

androidx.lifecycle:lifecycle-process:2.0.0

Libraries

app_lifecycle