本文件提供完整的 Firebase 雲端訊息配置指南 (FCM) 適用於你的 Flutter 行動應用程式,適用於 Android 和 iOS 平台。
建立新專案或選擇現有專案。
在 Firebase 專案中註冊你的應用程式(包括 Android 和 iOS)。
從 Firebase 控制台下載檔案。google-services.json
把檔案放進你的 Flutter 專案目錄。google-services.jsonandroid/app
buildscript {
dependencies {
// Add this classpath
classpath 'com.google.gms:google-services:4.3.15'
}
}在檔案底部加上以下一行:
apply plugin: 'com.google.gms.google-services'在以下區塊新增 Firebase 訊息相依:dependencies
implementation 'com.google.firebase:firebase-messaging:24.2.0'在標籤中加入必要的權限與服務宣告:<application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application ...>
<service
android:name=".MyFirebaseMessagingService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>從 Firebase 控制台下載檔案。GoogleService-Info.plist
把檔案放進你的 Flutter 專案目錄。GoogleService-Info.plistios/Runner
cd ios
pod installplatform :ios, '10.0'
use_frameworks!匯入所需模組並設定 Firebase:
import UIKit
import Flutter
import FirebaseCore
import FirebaseMessaging
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [String: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
Messaging.messaging().appDidReceiveMessage(userInfo)
super.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
}
}import UserNotifications
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
func application(_ application: UIApplication,
didReceive notification: UILocalNotification) {
print("Notification received: \(notification)")
}dependencies:
flutter:
sdk: flutter
firebase_core: ^2.10.0
firebase_messaging: ^14.0.0import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
@override
void initState() {
super.initState();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Message received: ${message.messageId}');
// Handle foreground messages here
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('FCM Demo'),
),
body: Center(
child: Text('Hello World'),
),
);
}
}Android:使用 Firebase 主控台發送測試訊息,或使用套件在本地測試訊息。firebase_messaging
iOS:確保你有真實的裝置,或用模擬器來測試 推 通知, 因為推播通知在 iOS 模擬器上無法運作。
遵循以下步驟將有助於你成功配置 Firebase 雲端訊息(FCM) 為 你的 Flutter 行動應用程式在 Android 和 iOS 平台上都能使用