Flutter 推送通知实战:基于 Firebase Cloud Messaging 的 push_notifications 示例深度解析

原创2026-10-14 13:44:411,769 阅读
文章标签:示例工程移动开发

Flutter 推送通知实战:基于 Firebase Cloud Messaging 的 push_notifications 示例深度解析

导读

推送通知(Push Notification)是移动应用中触达用户最直接的手段之一,而 Firebase Cloud Messaging(FCM)是跨 Android 与 iOS 的标准化推送通道。本文以 flutter-examples 仓库中的 push_notifications 示例应用为骨架,完整讲解在 Flutter 工程中接入 Firebase、配置双端原生工程、编写 Dart 侧消息回调与 UI 展示的完整流程。读完本文,你将掌握一个可运行的 FCM 推送 Demo 的全部接入步骤,理解 onMessage、onResume、onLaunch 三类回调的语义差异,并了解 Android Embedding v2 等版本前提带来的配置要求。

一、示例项目概览

push_notifications 是 flutter-examples 仓库中专门演示"接入 Firebase 云消息推送"的独立应用。它只做一件事:App 启动后订阅 Firebase 推送通道,收到推送消息时把消息的标题(title)与正文(body)解析出来,并在页面中央显示,同时弹出一个圆角 AlertDialog 展示通知内容。

从目录结构看,这是一个标准的 Flutter 工程骨架,包含完整的双端原生工程:

  • lib/main.dart:Dart 侧全部业务逻辑,包含 MyApp、MyHomePage 以及 notification() 弹窗函数;
  • pubspec.yaml:声明 firebase_core、firebase_messaging、firebase_analytics 三个 Firebase 相关依赖;
  • android/:Android 原生工程,其中 build.gradle 已挂载 Google Services 插件,AndroidManifest.xml 已声明通知点击所需的 Intent Filter;
  • ios/:iOS 原生工程,AppDelegate.swift 为标准 Flutter 入口,另有 Podfile 供 CocoaPods 拉取 Firebase 插件。

整个示例的代码量非常精简,非常适合作为"第一个 FCM 接入项目"来阅读。

二、前置条件与版本要求

README 的 Getting Started 部分明确了两个关键前提,这也是很多初学者踩坑的源头:

1. Flutter 版本必须 ≥ 1.22

This app works in versions >= Flutter 1.22 as it supports android embedding v2. Run flutter upgrade before running this app

原因在于 Android Embedding v2。Flutter 1.22 之后的默认 Android 模板与插件注册机制全面切换到 v2 嵌入方式,firebase_messaging 等插件依赖该机制完成原生能力桥接。如果本机 Flutter 版本过低,直接运行会报插件注册失败或消息收不到。仓库在 AndroidManifest.xml 中也通过如下 meta-data 显式声明了 v2 嵌入:

<meta-data
    android:name="flutterEmbedding"
    android:value="2" />

2. 必须与 Firebase 项目关联

This app can only work if connected with firebase.

推送通道本身依赖 FCM 服务端下发消息,因此没有 Firebase 项目配置,应用无法独立演示推送功能。完整接入需要三步:创建 Firebase 项目、把 google-services.json 放进 Android app 目录、在 Firebase Console 的 Cloud Messaging 中发送测试消息。

3. 依赖版本会过时,以 pub.dev 为准

Versions maybe be different you should check the latest packages from pub.dev

README 明确提示:仓库锁定的版本可能已过时,接入时应前往 pub.dev 核对最新稳定版本。这是本示例最具"时效性提醒"价值的一句话——Firebase 相关插件的大版本升级往往会伴随 API 变更(详见下文第九节)。

三、依赖配置:pubspec.yaml 中的三个 Firebase 包

示例在 pubspec.yaml 中声明了三个依赖,职责各不相同:

dependencies:
  firebase_analytics: ^6.0.1
  firebase_messaging: ^7.0.2
  firebase_core: ^0.5.0
依赖 版本(示例) 职责
firebase_core ^0.5.0 Firebase SDK 的基础核心包,负责初始化 Firebase App,其他所有 Firebase 插件都依赖它
firebase_messaging ^7.0.2 FCM 消息接收与处理的核心插件,提供 FirebaseMessaging 单例与各类回调
firebase_analytics ^6.0.1 Firebase Analytics 统计插件,在推送 Demo 中主要作为 Firebase 生态附加项

其中真正驱动推送逻辑的是 firebase_messaging。示例工程中这三个包对应的 Android 原生依赖也已同步配置在 build.gradle:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-messaging:20.3.0'
}
apply plugin: 'com.google.gms.google-services'

README 中"All the dependencies required to integrate Firebase project are added but you may need to update there versions"与"Dependencies and plugins for Firebase messaging packages are already added and you may not need to change anything for this"两句话,即是对上面 Dart 与 Gradle 两侧依赖已就绪的说明:直接 clone 后主要工作是更新版本、接入自己的 Firebase 项目,而不是补依赖。

四、Firebase 项目接入与 google-services.json

这是让 Demo 真正跑起来的必经步骤,README 给出了核心动作:

You need to create new firebase project on firebase console and add the google-services.json file in app folder of project

具体操作链路如下:

  1. 打开 Firebase Console,创建一个新的 Firebase 项目(或复用已有项目);
  2. 在项目设置中添加一个 Android 应用,包名要与 build.gradle 中的 applicationId 一致(示例中为 github.nisrulz.push_notifications,替换为自己的包名即可);
  3. 下载生成的 google-services.json,放到 android/app/ 目录下(README 所说的 "app folder of project" 即 push_notifications/android/app/);
  4. 如需 iOS 演示,在 Firebase Console 中再添加 iOS 应用并下载 GoogleService-Info.plist。

之所以必须存在 google-services.json,是因为 build.gradle 末尾通过 apply plugin: 'com.google.gms.google-services' 挂载了 Google Services 插件,Gradle 构建时该插件会读取这个 JSON 文件,把 applicationId、API Key、项目编号等凭据注入到 Android 资源中;文件缺失时构建阶段即会报错。

Android 侧的 Application 类也已就位:Application.java 继承自 FlutterApplication,并在 AndroidManifest.xml 中被指定为应用入口,为插件初始化(含 Firebase)提供了宿主。

五、Android 原生配置:通知点击 Intent Filter 与权限

推送通知在 Android 上要正常工作,除了 Firebase 配置,还依赖清单文件中的两项声明。

1. 通知点击的 Intent Filter

AndroidManifest.xml 在主 Activity 上注册了 FLUTTER_NOTIFICATION_CLICK:

<intent-filter>
  <action android:name="FLUTTER_NOTIFICATION_CLICK" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

该 Intent Filter 是 Flutter 插件层识别"用户点击了通知栏里的推送消息"这一事件的关键——点击通知后系统会把携带消息数据的 Intent 路由回 FlutterActivity,进而触发 Dart 侧的 onResume/onLaunch 回调(详见第七节)。

2. 网络权限

INTERNET 权限位于 debug/AndroidManifest.xml 与 profile/AndroidManifest.xml(Flutter 模板默认只在 debug/profile 变体声明,用于热重载等调试通信),确保应用在开发调试阶段能与 FCM 服务通信。

3. 其他工程参数

build.gradle 中 compileSdkVersion 29、minSdkVersion 16、targetSdkVersion 29 是当时(Flutter 1.22 时代)的合理取值;gradle.properties 中 android.useAndroidX=true 与 android.enableJetifier=true 则是 Firebase 插件在 AndroidX 环境下运行的必要开关。

六、iOS 原生配置与权限请求

iOS 端的原生配置相对简单。示例的 AppDelegate.swift 是 Flutter 模板标准实现:

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

GeneratedPluginRegistrant.register(with: self) 会把 pubspec 中声明的所有插件(含 firebase_messaging)注册到 iOS 运行时。iOS 推送还依赖 CocoaPods 安装插件,Podfile 已按 Flutter 标准模板配置好 flutter_install_all_ios_pods,执行 pod install 即可。

与 Android 不同,iOS 必须显式请求通知权限,这一逻辑体现在 Dart 侧(见第七节 requestNotificationPermissions 的调用)。README 中"All the dependencies required ... are added"同样适用于 iOS 侧,无需手工修改原生文件即可运行。

七、Dart 侧核心实现:消息格式与三类回调

示例全部 Dart 逻辑集中在 main.dart,入口非常简洁:

void main() => runApp(MyApp());

MyApp 是一个标准的 MaterialApp,home 为 MyHomePage。真正的推送逻辑在 _MyHomePageState 中,代码注释(main.dart)首先给出了 FCM 消息的标准结构:

{
  "notification": {
    "title": "Custom Title that we send from firebase cloud messaging",
    "body": "Text of the message will appear here"
  },
  "data": {
    "Here the extra data like if we include image, etc optional data from firebase cloud messaging"
  }
}

即:notification 段承载用户可见的标题与正文;data 段承载自定义业务数据(例如图片地址、跳转参数等)。

1. iOS 权限请求

在 initState 中,示例首先针对 iOS 请求通知权限(注释明确指出 Android 无需此步):

_firebaseMessaging.requestNotificationPermissions(
    const IosNotificationSettings(
        sound: true, badge: true, alert: true, provisional: true));

IosNotificationSettings 中的 sound、badge、alert 分别对应锁屏/横幅通知的声音、角标与弹窗提醒,provisional 为临时授权模式(用户未显式同意时也可静默展示通知)。

2. 三类回调的注册

随后调用 _firebaseMessaging.configure(...) 同时注册三个回调(main.dart):

_firebaseMessaging.configure(
  onMessage: (message) async {
    setState(() {
      title = message["notification"]["title"];
      messageData = message["notification"]["body"];
      notification(context, title, messageData);
    });
  },
  onResume: (message) async { /* 同样的解析与展示逻辑 */ },
  onLaunch: (message) async { /* 同样的解析与展示逻辑 */ },
);

三个回调对应三种不同的消息到达场景,这是 FCM 推送理解的核心:

回调 触发场景
onMessage 应用处于前台运行时收到推送消息
onResume 应用处于后台,用户点击通知栏消息将应用带回前台时触发
onLaunch 应用未启动(进程被杀),用户点击通知消息冷启动应用时触发

无论哪个回调,示例都执行同一套处理:从 message["notification"]["title"] 与 message["notification"]["body"] 取出标题和正文,通过 setState 更新界面,并调用 notification() 弹出对话框。

3. 消息展示 UI

页面主体(main.dart)是一个居中的 Column,顶部大号标题显示消息标题,下方次级文字显示消息正文,初始占位文案分别是 "Title will appear here" 与 "Message text will appear here",收到推送后即被真实内容替换。

4. 弹窗函数

notification()(main.dart)使用 showDialog 弹出 AlertDialog:barrierDismissible: false 使点击遮罩不会关闭弹窗,RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)) 提供圆角外观,标题与正文以不同字号/字重排列,底部一个 Ok 按钮通过 Navigator.pop 关闭。这样用户在收到推送的瞬间,无论在前台还是从后台点入,都能立刻看到完整通知内容。

八、发送测试推送:Firebase Console 操作要点

示例在 main.dart 的注释中给出了测试推送的官方路径:

For sending Push notification go to Grow and then cloud messaging, from there send new message by adding title and other fields as per requirement

即:在 Firebase Console 中进入 Grow → Cloud Messaging,点击发送新消息(Send your first message),填写:

  • Notification title:对应消息 JSON 中的 notification.title;
  • Notification text / body:对应 notification.body;
  • 发送目标选择已注册到该 Firebase 项目的测试设备(首次启动 App 时会自动完成设备注册);
  • 如需携带自定义数据,可在 Advanced options 中追加键值对,对应 data 段。

发送后即可验证三类场景:App 在前台时消息触发 onMessage 弹窗;按 Home 键退到后台后收到消息再点击通知栏,触发 onResume;杀掉进程后点击通知冷启动,触发 onLaunch。

九、运行方式与注意事项

运行命令:进入 push_notifications/ 目录后执行标准 Flutter 命令:

flutter pub get
flutter run

由于工程已配置好 Android/iOS 原生侧,只要 google-services.json 放置正确且设备/模拟器已安装 Google Play 服务,即可在 debug 模式跑通推送链路。

关于仓库内测试文件的一个说明:push_notifications/test/widget_test.dart 仍是 Flutter 模板生成的"计数器递增"冒烟测试(find.text('0')、Icons.add 等断言),与示例实际的推送 UI 并不匹配。从源码结构看,它属于创建工程时遗留的默认测试,运行 flutter test 会因 MyApp 中不存在计数器而失败,阅读与二次开发时可将其替换为针对消息解析逻辑的测试,不影响 App 本身运行。

版本演进提示:本示例锁定的 firebase_messaging: ^7.0.2 属于旧版 API 形态(configure、requestNotificationPermissions、IosNotificationSettings 等)。README 已明确建议以 pub.dev 上的最新版本为准,而新版 firebase_messaging 对前台消息、后台点击等场景的注册方式有较大调整(例如回调命名与权限请求 API 均发生变化)。因此,若你在新工程中按最新版本文档接入,示例中的调用写法需要同步迁移;若想 1:1 复现本文演示效果,则可按 README 建议将 Flutter 升级到支持 Android Embedding v2 的版本(≥ 1.22)并使用仓库锁定的依赖版本。

十、总结:一个最小可用的 FCM 推送闭环

纵观整个示例,push_notifications 完整覆盖了 FCM 推送的四层闭环:

  1. 依赖层:pubspec.yaml 声明 firebase_core、firebase_messaging、firebase_analytics,Gradle 侧同步挂载 Google Services 插件;
  2. 原生配置层:Android 清单声明 FLUTTER_NOTIFICATION_CLICK Intent Filter 与 v2 嵌入标记,iOS 由 AppDelegate 注册插件、Dart 侧请求通知权限;
  3. 业务逻辑层:FirebaseMessaging.configure 注册 onMessage/onResume/onLaunch 三类回调,统一解析 notification 段并驱动 UI 更新;
  4. 用户反馈层:页面文本实时刷新 + 圆角 AlertDialog 弹窗展示推送内容。

在此基础上,你可以沿着同样的接入路径扩展自己的推送方案:在 data 段携带业务标识实现跳转路由、接入本地通知插件做富文本推送、或升级到新版 firebase_messaging API 以获得更现代的注册方式。这也是 flutter-examples 仓库把该示例与 analytics_integration、firebase_crash_reporting 等 Firebase 系列示例并列放置的原因——它们共同构成了 Flutter 生态内 Firebase 能力的入门拼图。

登录后查看全文
flutter-examples