Flutter自定义FCM推送插件fcm_customizer的使用

Flutter自定义FCM推送插件fcm_customizer的使用

该插件允许你在Android和iOS平台上自定义FCM通知。


### 警告:插件处于早期开发阶段

完整示例代码

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

import 'package:flutter/services.dart';
import 'package:fcm_customizer/fcm_customizer.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = '未知';
  final _fcmCustomizerPlugin = FcmCustomizer();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 平台消息异步处理,因此我们在这里初始化
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用try/catch来捕获PlatformException。
    // 我们还处理了消息可能返回null的情况。
    try {
      platformVersion =
          await _fcmCustomizerPlugin.getPlatformVersion() ?? '未知平台版本';
    } on PlatformException {
      platformVersion = '获取平台版本失败。';
    }

    // 如果在异步平台消息还在飞行时,小部件从树中被移除,我们应该丢弃回复而不是调用setState来更新我们的不存在的外观。
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Text('运行在: $_platformVersion\n'),
        ),
      ),
    );
  }
}

更多关于Flutter自定义FCM推送插件fcm_customizer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义FCM推送插件fcm_customizer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


fcm_customizer 是一个用于 Flutter 的自定义 Firebase Cloud Messaging (FCM) 插件,允许开发者更灵活地处理推送通知。通过这个插件,你可以自定义通知的显示方式、处理通知点击事件、以及处理后台和前台的通知。

以下是如何使用 fcm_customizer 插件的步骤:

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 fcm_customizer 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  fcm_customizer: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 配置 Firebase

确保你已经按照 Firebase 的官方文档配置了 Flutter 项目中的 Firebase。你需要完成以下步骤:

  • Firebase 控制台 中创建一个项目。
  • google-services.json(Android)和 GoogleService-Info.plist(iOS)文件添加到你的 Flutter 项目中。
  • android/app/build.gradle 文件中添加以下依赖:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'  // 添加这一行

dependencies {
    implementation platform('com.google.firebase:firebase-bom:29.0.0')  // 使用最新版本
    implementation 'com.google.firebase:firebase-messaging'
}

3. 初始化 FCM

在你的 Flutter 应用的 main.dart 文件中,初始化 FCM 并配置 fcm_customizer 插件:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 FCM
  await FcmCustomizer.initialize();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FCM Customizer Example',
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FCM Customizer Example'),
      ),
      body: Center(
        child: Text('Welcome to FCM Customizer!'),
      ),
    );
  }
}

4. 处理通知

你可以通过 FcmCustomizer 来处理前台和后台的通知。

处理前台通知

在前台接收到通知时,你可以自定义通知的显示方式:

FcmCustomizer.onMessage.listen((RemoteMessage message) {
  print('Received a message in the foreground!');
  print('Message data: ${message.data}');

  // 自定义通知的显示方式
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('New Notification'),
        content: Text(message.notification?.title ?? 'No title'),
        actions: <Widget>[
          TextButton(
            child: Text('OK'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
});

处理通知点击事件

当用户点击通知时,你可以处理点击事件并导航到特定的页面:

FcmCustomizer.onMessageOpenedApp.listen((RemoteMessage message) {
  print('Notification clicked!');
  print('Message data: ${message.data}');

  // 导航到特定页面
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => NotificationDetailScreen(message: message),
    ),
  );
});

处理后台通知

后台通知的处理方式与前台通知类似,但你需要在 onBackgroundMessage 中处理:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('Handling a background message: ${message.messageId}');
  // 处理后台通知
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 设置后台消息处理
  FcmCustomizer.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  await FcmCustomizer.initialize();

  runApp(MyApp());
}

5. 发送测试通知

你可以通过 Firebase 控制台或使用 Postman 发送测试通知来验证你的 FCM 配置是否正确。

6. 自定义通知

fcm_customizer 允许你完全自定义通知的显示方式。你可以使用 flutter_local_notifications 插件来显示自定义通知。

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

void showNotification(RemoteMessage message) async {
  const AndroidNotificationDetails androidPlatformChannelSpecifics =
      AndroidNotificationDetails(
    'your_channel_id',
    'your_channel_name',
    importance: Importance.max,
    priority: Priority.high,
  );

  const NotificationDetails platformChannelSpecifics =
      NotificationDetails(android: androidPlatformChannelSpecifics);

  await flutterLocalNotificationsPlugin.show(
    0,
    message.notification?.title,
    message.notification?.body,
    platformChannelSpecifics,
    payload: 'item x',
  );
}

7. 处理权限

在某些平台上,你可能需要请求通知权限:

FcmCustomizer.requestPermission();

8. 获取设备 Token

你可以获取设备的 FCM Token 并将其发送到你的服务器:

String? token = await FcmCustomizer.getToken();
print('FCM Token: $token');

9. 注销 Token

如果需要,你可以注销设备的 FCM Token:

await FcmCustomizer.deleteToken();

10. 处理错误

你可以监听 FCM 的错误:

FcmCustomizer.onError.listen((error) {
  print('FCM Error: $error');
});
回到顶部