Hi my notification works fine it also gives vibrate to phone but the icon and the notification is not showing on screen, u have to slider down and u can see it in upper menu. how can I make to show in screen
The app page, I want to show little icon here
The upper menu on the phone is
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
#override
void initState() {
super.initState();
_advertService.showBanner();
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
final android = AndroidInitializationSettings('#mipmap/ic_launcher');
final iOS = IOSInitializationSettings();
final initSettings = InitializationSettings(android, iOS);
flutterLocalNotificationsPlugin.initialize(initSettings,
onSelectNotification: _onSelectNotification);
}
Future<void> _onSelectNotification(String json) async {
final obj = jsonDecode(json);
if (obj['isSuccess']) {
OpenFile.open(obj['filePath']);
} else {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Error'),
content: Text('${obj['error']}'),
),
);
}
}
Future<void> _showNotification(Map<String, dynamic> downloadStatus) async {
final android = AndroidNotificationDetails(
'channel id', 'channel name', 'channel description',
priority: Priority.High, importance: Importance.Max);
final iOS = IOSNotificationDetails();
final platform = NotificationDetails(android, iOS);
final json = jsonEncode(downloadStatus);
final isSuccess = downloadStatus['isSuccess'];
await flutterLocalNotificationsPlugin.show(
0, // notification id
isSuccess ? 'Okay' : 'Fail',
isSuccess
? 'Downloaded'
: 'Failed',
platform,
payload: json);
}
first you will set Flutter Launcher Icons
Setup the config file
dev_dependencies:
flutter_launcher_icons: "^0.7.3"
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon/icon.png"
If you name your configuration file something other than flutter_launcher_icons.yaml or pubspec.yaml you will need to specify the name of the file when running the package.
Note: If you are not using the existing pubspec.yaml ensure that your config file is located in the same directory as it.
Run the package
flutter pub get
flutter pub run flutter_launcher_icons:main
use this plugin
Related
I use Firebase messaging in my Flutter app , I want to navigate to another screen when I click on the notification even my app is in foreground or background , I used many functions and it doesn't trigger the click event and I can't find anything can solve my problem .
When I click on the notification when app is in foreground or background , nothing happened because it navigate to the same page .
And when I click on the notification when app is terminated , it opens on Splash screen and go to the home not the screen that I want .
I added this intent-filter in my Manifest
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
And I added this to the Json object
"click_action": "FLUTTER_NOTIFICATION_CLICK",
And here is how can I get background FCM in the main.dart
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance', // id
'High Importance Notifications', // title
importance: Importance.high,
playSound: true);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
SessionManager sessionManager = SessionManager();
await Firebase.initializeApp();
//final sound = 'sound.mp3';
print('A bg message just showed up : ${message.messageId}');
final android = AndroidInitializationSettings('#mipmap/ic_launcher');
final ios = IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,);
final settings = InitializationSettings(android: android,iOS: ios);
flutterLocalNotificationsPlugin.initialize(settings,);
if(message.data['title'].toString().toLowerCase()=="new request") {
sessionManager.getBadge().then((badge) {
if (badge != null) {
int x = badge + 1;
sessionManager.saveBadge(x);
print("notification number is " + x.toString());
}
else {
sessionManager.saveBadge(1);
}
});
}
flutterLocalNotificationsPlugin.show(
message.data.hashCode,
message.data['title'],
message.data['body'],
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
importance: Importance.high,
priority: Priority.high,
// sound: RawResourceAndroidNotificationSound(sound.split('.').first),
playSound: true,
icon: '#mipmap/ic_launcher',
),
));
/*NotificationApi.showNotification(
title: message.data['title'],
body: message.data['body'],
payload: "",
id: int.parse(channel.id));*/
}
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
runApp(MyApps());
// configLoading();
}
class MyApps extends StatefulWidget {
const MyApps({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() {
return MyApp();
}
}
class MyApp extends State<MyApps> {
static ValueNotifier<int> strikeNotifier = ValueNotifier(0);
Color _primaryColor = Color(0xff0d8b75);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return ScreenUtilInit(
builder: () => MaterialApp(
debugShowCheckedModeBanner: false,
home: SplashScreen(),
),
designSize: const Size(1080, 2280),
);
}
void showNotification(String title, String body) async {
await _demoNotification(title, body);
}
Future<void> _demoNotification(String title, String body) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_I', 'channel name',
showProgress: true,
priority: Priority.high,
playSound: true,
ticker: 'test ticker');
var iOSChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
await flutterLocalNotificationsPlugin
.show(0, title, body, platformChannelSpecifics, payload: 'test');
}
#override
void initState() {
super.initState();
FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
if (message != null) {
Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));
}
});
getToken().then((value) {
if(value!=null) {
AppConstants.firebaseToken = value;
}
});
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
var data = message.data;
// AndroidNotification? android = message.notification?.android;/
if (data != null ) {
if(data['title'].toString().toLowerCase()=="new request") {
SessionManager sessionManager = SessionManager(context);
sessionManager.getBadge().then((badge) {
if (badge != null) {
setState(() {
int x = badge + 1;
strikeNotifier.value = x;
sessionManager.saveBadge(x);
});
}
else {
strikeNotifier.value = 1;
sessionManager.saveBadge(1);
}
});
}
print("entered");
flutterLocalNotificationsPlugin.show(
data.hashCode,
data['title'],
data['body'],
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
playSound: true,
icon: '#mipmap/ic_launcher',
),
));
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));
});
}
Future<String?> getToken() async{
String? token = await FirebaseMessaging.instance.getToken();
print("token is "+token!);
return token;
}
}
In yaml
firebase_core: ^1.12.0
firebase_messaging: ^11.2.6
dependency_overrides:
firebase_messaging_platform_interface: 3.1.6
Edit : from multiple solutions , I tried the most common solution that I used onMessageOpenedApp in initState but it doesn't enter in it
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));
});
In your code, you are using the flutter_local_notifications plugin and you are creating local notification when you get a push notification from firebase messaging.
Since the notification is not created by firebase messaging so, you are not getting on tap callback in getInitialMessage and onMessageOpenedApp.
In order to get on tap callback on local notifications, you can pass a callback function while initializing flutter_local_notifications
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
void selectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: $payload');
// Here you can check notification payload and redirect user to the respective screen
await Navigator.push(
context,
MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
);
}
}
For more, you can check flutter_local_notifications documentation
On your home widget within initState, check the getInitialMessage value :
// get the remote message when your app opened from push notification while in background state
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
// check if it is exists
if (initialMessage != null) {
// check the data property within RemoteMessage and do navigate based on it
}
Check the firebase flutter documentation here https://firebase.flutter.dev/docs/messaging/notifications/#handling-interaction.
Use onMessageOpenedApp stream to listen when a notification is opened in the foreground or background. When the application is terminated, use getInitialMessage to get a pending notification.
I am working on a flutter app. I am creating a pdf file in the "Downloads" folder, after creating the file in the "Downloads" folder, showing a notification "Download Completed" using the "local_notification" plugin.
Now I want to show that pdf when the user clicks on the notification. Can anybody guide me on how I can do that?
Below is my code
final android = AndroidNotificationDetails('0', 'Adun Accounts',
channelDescription: 'channel description',
priority: Priority.high,
importance: Importance.max,
icon: '');
final iOS = IOSNotificationDetails();
final platform = NotificationDetails(android: android, iOS: iOS);
await flutterLocalNotificationsPlugin.show(
0, // notification id
fileName,
'Download complete.',
platform);
show() has a parameter called payload , you can pass the path to the pdf file here. Add the plugin open_file in your pubspec.yaml. Then inside main.dart, add the following code
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> initNotification() async {
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('notification_icon');
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings();
final MacOSInitializationSettings initializationSettingsMacOS =
MacOSInitializationSettings();
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
macOS: initializationSettingsMacOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String? payload) {
if (payload != null) OpenFile.open(payload);
});
}
Note: This function should not be inside any class.
Here is my code below :
const AndroidNotificationChannel notificationChannel = AndroidNotificationChannel(
'high_importance_channel',
'high importance Notificaion',
'this channel is used for import notification',
importance: Importance.high,
playSound: true,
);
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> firebaseBackgroundMessageHandler(RemoteMessage message) async {
await firebaseMessageHandler(message);
}
Future<void> firebaseForegroundMessageHandler(RemoteMessage message) async {
await firebaseMessageHandler(message);
}
Future<void> firebaseMessageHandler(RemoteMessage message) async {
await Firebase.initializeApp();
try {
flutterLocalNotificationsPlugin.show(
message.notification.hashCode,
message.data["title"].toString(),
message.data["body"].toString(),
NotificationDetails(
android: AndroidNotificationDetails(notificationChannel.id, notificationChannel.name, notificationChannel.description),
));
} catch (_err) {}
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(firebaseBackgroundMessageHandler);
FirebaseMessaging.onMessage.listen(firebaseForegroundMessageHandler);
//FirebaseMessaging.onMessageOpenedApp.listen(firebaseMessageHandler);
final AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('e_app');
final InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(notificationChannel);
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(alert: true, badge: true, sound: true);
}
The code is working fine for a single notification but whenever I send multiple notifications to android, it shows only the last notification in the status bar.
Could anyone help me about
how to show multiple notifications in the status bar using the flutter local notification plugin?
If you want to group your notifications, there is an option to do that in flutter_local_notifications.
To do this, you can add the following in your code
for ios : threadIdentifier in IOSNotificationDetails
for android : groupChannelId, groupChannelName, groupChannelDescription,
You can find these in the docs here: https://pub.dev/packages/flutter_local_notifications#displaying-a-notification under 'Grouping notifications'.
Basically notifications under same threadId or groupId will all be grouped and shown
I am trying to navigate to a specific page using local notification, the moment the user touches the notification, below I leave the code of how I am doing it, basically, the problem is when onSelectNotification is called everything that is before is executed but Once Navigator.push is called, it does not go to the screen that I tell it and it does not raise any exceptions and what is after is not executed either.
/// Allows you to navigate to a specific screen from the notification
Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('Notification payload: $payload');//it shows
}
await Navigator.push(context, MaterialPageRoute(builder: (context) => AnyScreen()));
debugPrint("go to AnyScreen");//does not show it
}
#override
void initState() {
// TODO: implement initState
super.initState();
/// local notication inicialization
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.max,
);
FlutterLocalNotificationsPlugin flip =
new FlutterLocalNotificationsPlugin();
flip
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
const AndroidInitializationSettings android =
AndroidInitializationSettings('app_icon');
final IOSInitializationSettings iOS = IOSInitializationSettings();
final MacOSInitializationSettings macOS = MacOSInitializationSettings();
final InitializationSettings initializationSettings =
InitializationSettings(android: android, iOS: iOS, macOS: macOS);
flip.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
/// listen when the app is open
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
// If `onMessage` is triggered with a notification, construct our own
// local notification to show to users using the created channel.
if (notification != null && android != null) {
flip.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id, channel.name, channel.description,
icon: android?.smallIcon,
// other properties...
priority: Priority.high),
));
}
});
}
...
I tried the following code. It's giving 'MissingPluginException' is not a subtype of type 'String'
Below is the code I used (pasted only notification part here). No issue in flutter doctor also.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class _Home extends State<HomePage> with TickerProviderStateMixin {
static FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
#override
void initState() {
super.initState();
firebaseCloudMessaging_Listeners();
}
void firebaseCloudMessaging_Listeners() {
var android = new AndroidInitializationSettings('mipmap/ic_launcher',);
var ios = new IOSInitializationSettings();
var platform = new InitializationSettings(android, ios);
flutterLocalNotificationsPlugin.initialize(platform,onSelectNotification: onSelectNotification);
if (Platform.isIOS) iOS_Permission();
_firebaseMessaging.getToken().then((token){
//FCM=token;
}).catchError((onError){
print("blb07 "+onError.toString());
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('blb07 on message $message');
handleNotification(message['data']['message']);
},
onResume: (Map<String, dynamic> message) async {
print('blb07 on resume $message');
handleNotification(message['data']['message']);
},
onLaunch: (Map<String, dynamic> message) async {
print('blb07 on launch $message');
handleNotification(message['data']['message']);
},
);
}
void iOS_Permission() {
_firebaseMessaging.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true)
);
_firebaseMessaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings)
{
print("Settings registered: $settings");
});
}
Future onSelectNotification(String payload) async {
await Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new DisplayNotifications()),
);
}
void handleNotification(String message) async{
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'default1', 'Sureworks ', 'Sureworks app notifications',
importance: Importance.Max, priority: Priority.High);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
print("blb07 start");
try{
await flutterLocalNotificationsPlugin.show(0, 'Sureworks', message, platformChannelSpecifics,payload: 'item')
.then((onValue){
print("blb07 finished");
}).catchError((onError)=>print("blb07 "+onError));
print("blb07 hello end line");
}catch(e){
print("blb07 error "+e.toString());
}
}
}
my pubspec.yaml dependencies
dev_dependencies:
flutter_test:
sdk: flutter
http: ^0.11.3+16
shared_preferences: ^0.4.2
firebase_messaging: ^4.0.0+1
firebase_core: ^0.2.5
flutter_launcher_icons: ^0.7.0
paging: ^0.1.0
flutter_local_notifications: ^0.6.1
What could be the problem? messages passing to the handleNotification funtion are string format only. No problem in Receiving notification data from server.
Did you run pod install ?
If not its likely that there is something missing on the native side.
Simply open up a terminal and navigate to your flutter project root.
Then cd into the iOS folder and run pod install.
This should fix your error.
I found the solution. Migrated my Android to AndroidX. Now it's working fine. Spent more than 4 hours on it.
Migrate to AndroidX and "Invalidate caches and restart" did the trick.