Skip to content

Instantly share code, notes, and snippets.

@shashank-p
Created February 18, 2020 05:53
Show Gist options
  • Save shashank-p/1b1bea36f01da091a6c8d17646ba6871 to your computer and use it in GitHub Desktop.
Save shashank-p/1b1bea36f01da091a6c8d17646ba6871 to your computer and use it in GitHub Desktop.
firebase push notification in flutter (Sample Code)
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class MyAppsPage extends StatelessWidget {
return MaterialApp(
home: HomePage(title: 'Firebase'),
);
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_AppsPageState createState() => _AppsPageState();
}
class _AppsPageState extends State<HomePage> {
FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
@override
void initState() {
super.initState();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
print('on message $message');
showNotification(message);
},
onResume: (Map<String, dynamic> message) {
print('on resume $message');
},
onLaunch: (Map<String, dynamic> message) {
print('on launch $message');
},
);
_firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.getToken().then((token) {
fcm_token = token;
print(token);
});
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
var iOS = new IOSInitializationSettings();
var initSetttings = new InitializationSettings(android, iOS);
flutterLocalNotificationsPlugin.initialize(initSetttings,
onSelectNotification: onSelectNotification);
}
@override
Widget build(BuildContext context) {
return Scaffold();
}
Future onSelectNotification(String payload) {
showDialog(
context: context,
builder: (_) =>
new AlertDialog(
title: new Text('Notification'),
content: new Text('$payload'),
),
);
}
showNotification(Map<String, dynamic> message) async {
var android = new AndroidNotificationDetails(
'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
priority: Priority.High, importance: Importance.Max);
var iOS = new IOSNotificationDetails();
var platform = new NotificationDetails(android, iOS);
await flutterLocalNotificationsPlugin.show(0, 'Message Title,',
'Test Message Body', platform,
payload: 'Test Message (you can put notification msg)');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment