-
-
Save khomkrit/64c3f9dc0cd8fc79f7b1a6efee8b1b92 to your computer and use it in GitHub Desktop.
Flutter Push Notification / APNs with Firebase Cloud Messaging (FCM) Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:firebase_core/firebase_core.dart'; | |
import 'package:firebase_messaging/firebase_messaging.dart'; | |
import 'package:flutter/material.dart'; | |
import 'firebase_options.dart'; | |
void main() async { | |
WidgetsFlutterBinding.ensureInitialized(); | |
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); | |
runApp(const MaterialApp(home: App())); | |
} | |
class App extends StatefulWidget { | |
const App({Key? key}) : super(key: key); | |
@override | |
State<StatefulWidget> createState() => _AppState(); | |
} | |
Future<void> _firebaseMessagingHandler(RemoteMessage message) async { | |
debugPrint('Notification: ${message.notification?.title ?? ''}'); | |
} | |
class _AppState extends State<App> { | |
String _message = ''; | |
@override | |
void initState() { | |
super.initState(); | |
_initFirebase(); | |
_setupInteractedMessage(); | |
} | |
Future<void> _initFirebase() async { | |
bool allow = await _requestPermission(); | |
if (!allow) return; | |
debugPrint('device token = ${await FirebaseMessaging.instance.getToken()}'); | |
FirebaseMessaging.onMessage.listen(_firebaseMessagingHandler); | |
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingHandler); | |
} | |
void _setupInteractedMessage() async { | |
// Read messages which caused the application to open from | |
// a terminated state. | |
FirebaseMessaging messaging = FirebaseMessaging.instance; | |
RemoteMessage? initialMessage = await messaging.getInitialMessage(); | |
setState(() => _message = initialMessage?.notification?.title ?? 'No'); | |
// Also handle any interaction when the app is in the background | |
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { | |
setState(() => _message = message.notification?.title ?? 'No'); | |
}); | |
} | |
Future<bool> _requestPermission() async { | |
FirebaseMessaging messaging = FirebaseMessaging.instance; | |
NotificationSettings settings = await messaging.requestPermission( | |
alert: true, | |
badge: true, | |
provisional: false, | |
sound: true, | |
); | |
return (settings.authorizationStatus == AuthorizationStatus.authorized || | |
settings.authorizationStatus == AuthorizationStatus.provisional); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold(body: Center(child: Text(_message))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment