flutter 桌面通知 气泡消息数量

发布时间 2023-12-25 10:25:58作者: vx_guanchaoguo0

先上效果

原理

  • Android 操作系统提供的 NotificationManager 接口来设置应用程序图标上的徽章
  • iOS 操作系统提供的 UIApplication.shared.applicationIconBadgeNumber

使用flutter

flutter pub add flutter_app_badger         

通过在启动 退出时候更新气泡

import 'package:flutter/cupertino.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<StatefulWidget> createState() => _HomeScreenState();
}

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

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print("app in resumed");

        if (PushNotificationsManager.appBadgeSupported) {
          FlutterAppBadger.updateBadgeCount(14);
        }

        break;
      case AppLifecycleState.inactive:
        print("app in inactive");

        break;
      case AppLifecycleState.paused:
        print("app in paused");

        break;
      case AppLifecycleState.detached:
        print("app in detached");

        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}