新 전체코드
var token;
Future<void> getToken() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
await messaging.requestPermission();
token = await messaging.getToken();
print('토큰 : $token');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
getToken();
LocalNotification.initialize();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
showNotification(message);
});
super.initState();
}
@override
Widget build(BuildContext context) {
LocalNotification.requestPermission();
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
child: const Text('알림 띄우기'),
onPressed: () {
print('temp');
},
),
],
),
),
);
}
}
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class LocalNotification {
LocalNotification._();
static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
static initialize() async {
AndroidInitializationSettings initializationSettingsAndroid =
const AndroidInitializationSettings('favicon');
DarwinInitializationSettings initializationSettingsIos =
const DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true);
InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIos,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
static void requestPermission() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(alert: true, badge: true, sound: true);
}
}
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
final notifications = FlutterLocalNotificationsPlugin();
showNotification(RemoteMessage message) async {
var androidDetails = const AndroidNotificationDetails(
'유니크한 알림 채널 ID',
'알림종류 설명',
priority: Priority.high,
importance: Importance.max,
color: Color.fromARGB(255, 255, 0, 0),
);
var iosDetails = const DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
badgeNumber: 9999,
);
RemoteNotification? notification = message.notification;
notifications.show(
notification.hashCode,
notification!.title,
notification.body,
NotificationDetails(android: androidDetails, iOS: iosDetails),
);
}
舊 전체코드
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await setupFlutterNotifications();
showFlutterNotification(message);
}
var isFlutterLocalNotificationsInitialized = false;
var flutterLocalNotificationsPlugin;
var channel;
var initalizationsSetting;
var initalizationsSettingsIos;
var initalizationSettingsAndroid;
String? token;
Future<void> setupFlutterNotifications() async {
if (isFlutterLocalNotificationsInitialized) {
return;
}
channel = const AndroidNotificationChannel(
'high_importance_channel',
'High Importance Notifications',
description:
'This channel is used for important notifications.',
importance: Importance.high,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.requestPermissions(alert: true, badge: true, sound: true);
initalizationSettingsAndroid = AndroidInitializationSettings('defaultIcon');
initalizationsSettingsIos = DarwinInitializationSettings();
initalizationsSetting = InitializationSettings(
android: initalizationSettingsAndroid, iOS: initalizationsSettingsIos);
flutterLocalNotificationsPlugin.initialize(initalizationsSetting,
onDidReceiveNotificationResponse:
(NotificationResponse notificationResponse) async {
debugPrint('notificationResponse: $notificationResponse');
});
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
await FirebaseMessaging.instance.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
getTokenMth();
isFlutterLocalNotificationsInitialized = true;
}
Future<void> getTokenMth() async {
final fcm = FirebaseMessaging.instance;
await fcm.requestPermission();
token = await fcm.getToken();
}
void showFlutterNotification(RemoteMessage message) {
print("message : ===== ${message.toString()}");
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
icon: 'launch_background',
),
),
);
}
AppleNotification? apple = message.notification?.apple;
if (notification != null && apple != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
const NotificationDetails(iOS: DarwinNotificationDetails()),
);
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Firebase.apps.isEmpty) {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
} else {
Firebase.app();
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
await setupFlutterNotifications();
}
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _AppState();
}
class _AppState extends State<MyApp> {
void setupPushNotifications() async {
final fcm = FirebaseMessaging.instance;
await fcm.requestPermission();
token = await fcm.getToken();
}
@override
void initState() {
super.initState();
FirebaseMessaging.onMessage.listen(showFlutterNotification);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessageOpenedApp.listen((event) {
print('event: $event');
});
}
GoRouter get _router => GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (_, state) => WebViewVue(
token: token,
),
),
],
);
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
theme: ThemeData(fontFamily: 'NotoSans'),
debugShowCheckedModeBanner: false,
);
}
}