FCM 配置 2.4

Flutter Mobile App 的 FCM 配置

本文件提供完整的 Firebase 雲端訊息配置指南 (FCM) 適用於你的 Flutter 行動應用程式,適用於 Android 和 iOS 平台。

1. 建立Firebase計畫

2. 設定 Android for Firebase

2.1 將 Firebase SDK 加入您的 Android 專案

2.2 更新 'android/build.gradle'

buildscript {
    dependencies {
        // Add this classpath
        classpath 'com.google.gms:google-services:4.3.15'
    }
}

2.3 更新 'android/app/build.gradle'

apply plugin: 'com.google.gms.google-services'
implementation 'com.google.firebase:firebase-messaging:24.2.0'

2.4 更新「AndroidManifest.xml」

<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>

3. 設定 iOS 以支援 Firebase

3.1 將 Firebase SDK 加入您的 iOS 專案

3.2 安裝 CocoaPods 依賴

cd ios
pod install

3.3 更新「Podfile」

platform :ios, '10.0'
use_frameworks!

3.4 更新「AppDelegate.swift」

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)
    }
}

3.5 請求通知權限

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)")
}

4. 配置 Flutter 應用程式

4.1 新增 FlutterFire 插件

dependencies:
      flutter:
        sdk: flutter
      firebase_core: ^2.10.0
      firebase_messaging: ^14.0.0

4.2 在你的 Flutter 應用程式中初始化 Firebase

import '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'),
      ),
    );
  }
}

5. 測試你的設定

遵循以下步驟將有助於你成功配置 Firebase 雲端訊息(FCM) 為 你的 Flutter 行動應用程式在 Android 和 iOS 平台上都能使用