이번 카테고리는 Firebase Cloud Messaging 에 대해서 알아보겠습니다.
개발환경 : 윈도우11, 안드로이드 스튜디오, flutter 3.0.1
소스코드 위치 - Release 04_FCM_latest_upgrade · mike-bskim/FCM_test · GitHub
Release 04_FCM_latest_upgrade · mike-bskim/FCM_test
github.com
초기 화면은 아래와 같습니다.
기본적인 Firebase 설정은 아래 설정을 참고하세요. 1,2번까지만 설정하면 됩니다.
단, SHA1 부분은 필요없습니다.
(3. Firebase 프로젝트에서 구글 인증 활성화 부터 필요없습니다.)
2021.08.06 - [Flutter/01 SNS login] - [Flutter] SNS login (1) - Firebase 설정 및 Google 인증 활성화
[Flutter] SNS login (1) - Firebase 설정 및 Google 인증 활성화
기본 구성은 아래와 같습니다. 1. Firebase 프로젝트 생성 2. 안드로이드 관련 설정 3. 구글 인증 활성화 4. 이메일 로그인 활성화 Flutter 프로젝트 생성 후, 아래의 절차대로 진행하면 됩니다. 1. Firebas
unsungit.tistory.com
주요 설정 부분은 아래의 참고자료 유투브 링크를 참고하셔도 좋습니다. 소스코드에 추가된 부분도 참고하시기 바랍니다.
./android/app/build.gradle
./android/build.gradle
./android/app/src/main/AndroidManifest.xml
./android/app/src/main/res/values/strings.xml
패키지 버전은 현재 최신 버전을 사용했습니다.
firebase_core: ^1.19.1
firebase_messaging: ^11.4.4
get: ^4.6.5
main.dart
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:get/get.dart';
import 'src/app.dart';
import 'src/controller/notification_controller.dart';
void main() async {
// 최신 버전의 FCM 에서 필요한 설정
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
initialBinding: BindingsBuilder(
() {
Get.put(NotificationController());
},
),
home: const App(),
);
}
}
./lib/src/app.dart
import 'package:flutter/material.dart';
import 'package:push_notification/src/page/message_page.dart';
import 'package:get/get.dart';
import 'controller/notification_controller.dart';
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Firebase cloud Message"),
),
body: Obx(() {
// 메시지를 받으면 새로운 화면으로 전화하는 조건문
if (NotificationController.to.remoteMessage.value.messageId != null) {//message
return const MessagePage();
}
return const Center(
child: Text('Firebase cloud Message'),
);
}),
);
}
}
notification_controller.dart -
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());
}
}
[참고자료] 개발하는 남자 - https://www.youtube.com/watch?v=54woYKOrVUo
'Flutter > 04 Widgets' 카테고리의 다른 글
[Flutter] Widgets - Google map 5 (0) | 2022.07.03 |
---|---|
[Flutter] Widgets - Google map 4(Geolocator) (0) | 2022.07.02 |
[Flutter] Widgets - Google map 3(Place autocomplete) (0) | 2022.07.01 |
[Flutter] Widgets - Google map 2 (0) | 2022.06.30 |
[Flutter] Widgets - Google map (0) | 2022.06.28 |