firebase 메서지 설정 2023.10.27일 적용
오랜만에 플러터에서 firebase 메세지 설정을 구성해 보았다.
매번 프로젝트 생성하고 적용할때마다 버전이 약간식 변해서 그때마다 다시 설정정보를 보고 진행하게 된다.
현재 플러터 3.13.5 버전으로 2023 .10월 기준 firebase 사이트에서 json 파일을 생성해서 프로젝트에 적용한다.
PS C:\git\t_logis> flutter doctor (나의 플터러 적용환경)
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.13.5, on Microsoft Windows [Version 10.0.22621.2428], locale ko-KR)
[√] Windows Version (Installed version of Windows is version 10 or higher)
[√] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[√] Chrome - develop for the web
[√] Visual Studio - develop Windows apps (Visual Studio Build Tools 2019 16.11.29)
[√] Android Studio (version 2022.3)
[√] Connected device (4 available)
[√] Network resources
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
id 'com.google.gms.google-services'
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
android {
namespace "kr.co.tipsvalley.tlogis"
compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "kr.co.tipsvalley.tlogis"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.release
}
}
}
flutter {
source '../..'
}
dependencies {
implementation platform('com.google.firebase:firebase-bom:32.4.0')
}
만약 여기를 4.4.0 으로 했을때 아래 에러가 발생한다. 여러문서를 통해 버전호환 문제인듯해서 변경 적용 후 문제없이 처리되었다. PlatformException (PlatformException(null-error, Host platform returned null value for non-null return value., null, null))
pluginManagement {
def flutterSdkPath = {
def properties = new Properties()
file("local.properties").withInputStream { properties.load(it) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
return flutterSdkPath
}
settings.ext.flutterSdkPath = flutterSdkPath()
includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle")
plugins {
id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false
id 'com.google.gms.google-services' version '4.4.0' apply false
}
}
include ":app"
apply from: "${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle/app_plugin_loader.gradle"
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.15'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
KEY 파일 적용
KEY 파일 생성후( 다른 문서참조) 플러터 소스에 적용예
storePassword=XXXXX
keyPassword=XXXXX
keyAlias=XXXXXXX
storeFile=c:\\Users\\skpark\\.android\\XXXXX.keystore
pubspec.yaml 파일 설정
GETX 컨트롤러 파일 추가
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class NotificationController extends GetxController {
static NotificationController get to => Get.find();
// 최신버전의 초기화 방법
final FirebaseMessaging _messaging = FirebaseMessaging.instance;
Rx<RemoteMessage> remoteMessage = const RemoteMessage().obs;
// remoteMessage 가 obx 에서 검출이 잘되지 않아서 dateTime 을 추가함
Rx<DateTime> dateTime = DateTime.now().obs;
@override
void onInit() {
_initNotification();
// 토큰을 알면 특정 디바이스에게 문자를 전달가능
_getToken();
super.onInit();
}
void _getToken() {
_messaging.getToken().then((token) {
debugPrint('token~: [$token]');
});
}
void _initNotification() {
// 앱이 동작중일때 호출됨
FirebaseMessaging.onMessage.listen((RemoteMessage event) {
_addNotification(event);
debugPrint("NotificationController >> message received");
debugPrint('Title >> ${event.notification!.title.toString()}');
debugPrint('Body >> ${event.notification!.body.toString()}');
});
// 앱이 background 동작중일때 호출됨, 종료중일때도 호출됨?
FirebaseMessaging.onMessageOpenedApp.listen((message) {
_addNotification(message);
debugPrint('------------------------Message clicked!');
});
}
// 메시지를 변수에 저장
void _addNotification(RemoteMessage event) {
dateTime(event.sentTime);
remoteMessage(event);
// debugPrint(event.toMap().toString());
debugPrint(dateTime.toString());
}
}
메인다트 페이지에 초기화 셋팅
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
import 'core/app_export.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]).then((value) {
Logger.init(kReleaseMode ? LogMode.live : LogMode.debug);
runApp(MyApp());
});
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: theme,
translations: AppLocalization(),
locale: Get.deviceLocale, //for setting localization strings
fallbackLocale: Locale('en', 'US'),
title: 't_logis',
initialBinding: InitialBindings(),
initialRoute: AppRoutes.initialRoute,
getPages: AppRoutes.pages,
);
}
}
*** getx 콘트롤러 바인딩
플러터 디버깅 과정에서 토근 파일 찾아냄 나중에 로그인할때 서버에 토큰을 업데이트해서 메시지 보내는데 활용
firebase 에서 테스트로 캠페인 메세지를 보내봄
테스트 메세지가 보내짐