I have implemented local push notifications in flutter app. This plugin was working smoothly at first. The issues came when I had run flutter clean and also uninstalling the app on android Emulator to do a clean install with flutter run. After doing so the app crashes on startup.
When run the app in debugging mode, it is showing that the error is happening on await localNotificationsPlugin.initialize. Debugger showing statement below.
Exception has occurred.
PlatformException (PlatformException(INVALID_ICON, The resource ic_launcher could not be found. Please make sure it has been added as a drawable resource to your Android head project., null))
Code below is showing how I have implemented the localNotificationsPlugin.
FlutterLocalNotificationsPlugin localNotificationsPlugin =
FlutterLocalNotificationsPlugin();
initializeNotifications() async {
var initAndroid = AndroidInitializationSettings('ic_launcher');
var initIOS = IOSInitializationSettings();
var initSettings = InitializationSettings(initAndroid, initIOS);
await localNotificationsPlugin.initialize(
initSettings,
onSelectNotification: gotToNotificationsPage,
);
}
#override
void initState() {
super.initState();
initializeNotifications();
showNotification();
}
Future singleNotification(
DateTime datetime, String message, String subtext, int hashcode,
{String sound}) async {
var androidChannel = AndroidNotificationDetails(
'channel-id',
'channel-name',
'channel-description',
importance: Importance.Max,
priority: Priority.Max,
);
var iosChannel = IOSNotificationDetails();
var platformChannel = NotificationDetails(androidChannel, iosChannel);
localNotificationsPlugin.schedule(
hashcode, message, subtext, datetime, platformChannel,
payload: hashcode.toString());
}
showNotification() async {
DateTime now = DateTime.now().toUtc().add(
Duration(seconds: 5),
);
await singleNotification(
now,
'Notification',
'This is a notification',
98123871,
);
}
Future gotToNotificationsPage(String payload) {
return Navigator.pushNamed(context, '/notifications');
}
Note the problem is on await localNotificationsPlugin.initialize I'm failing to assign app Icon properly. Thank you.
To set a custom icon, you can add an app_icon.png inside android/app/src/res/drawable, then initialize it with
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');`
Otherwise, if you'd like to use the default app icon, you can set the app icon on AndroidInitializationSettings with #mipmap/ic_launcher
If you're unsure on where to start, you can try out the sample provided by the plugin on GitHub.
Related
I tried to add flutter app icon by using a package flutter_launcher_icon app icon is correct but icons shows in push notification show as a white box
Notification Icon Shows as a white box
Resource File
I added icons by using a package [flutter_launcher_icons]
Expected Output
same error have happened to me so i have used icon as xml file in android
we have to add that file name here
void showNotification(int orderCount) async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = AndroidInitializationSettings('fav_icon');
var initializeSettings = InitializationSettings(android: initializationSettingsAndroid);
var res = await flutterLocalNotificationsPlugin.initialize(initializeSettings) ?? false;
Log.d("Notification manager initialized $res");
if (res) {
flutterLocalNotificationsPlugin.show(
1,
"Order",
"You have new notifications",
NotificationDetails(
android: AndroidNotificationDetails('NOTIFICATION', 'New order notifications',
channelDescription: 'Shows notifications when new orders are available',
importance: Importance.max,
priority: Priority.high,
playSound: true,
category: AndroidNotificationCategory.event,
color: MyColor.kSecondary)));
}
}
so i'm creating an app like facebook,instagram ....
When i was in systeme notifications step, i managed to display notifications when the App state is Open or paused but not when the app is dettached (closed), i'm no longer able to recieve new local notifications.
i tried many packages like flutter_background_service and workmanager, i'm working with flutter_background_service now in debug mode all was good, but when i build the apk it's not working in background.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
AwesomeNotifications().initialize('resource://drawable/appicon', [
NotificationChannel(
channelKey: 'basic_channel',
channelName: 'basic Notifications',
channelDescription: "channelDescription",
importance: NotificationImportance.High,
enableVibration: true,
channelShowBadge: true,
)
]);
await Firebase.initializeApp(
name: 'firebase',
options: const FirebaseOptions(//firebaseconfig),
);
await initializeService();
runApp(MyApp());
}
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will be executed when app is in foreground or background in separated isolate
// auto start service
autoStart: true,
onStart: onStart,
isForegroundMode: false,
),
iosConfiguration: IosConfiguration(
// auto start service
autoStart: true,
// this will be executed when app is in foreground in separated isolate
onForeground: onStart,
// you have to enable background fetch capability on xcode project
onBackground: onIosBackground,
),
);
service.startService();
}
// to ensure this is executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
bool onIosBackground(ServiceInstance service) {
WidgetsFlutterBinding.ensureInitialized();
print('FLUTTER BACKGROUND FETCH');
return true;
}
void onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();
if (service is AndroidServiceInstance) {
service.on('setAsForeground').listen((event) {
service.setAsForegroundService();
});
service.on('setAsBackground').listen((event) {
service.setAsBackgroundService();
});
}
service.on('stopService').listen((event) {
service.stopSelf();
});
// bring to foreground
Timer.periodic(const Duration(seconds: 1), (timer) async {
/// you can see this log in logcat
print('FLUTTER BACKGROUND SERVICE is running : ${DateTime.now()}');
//////////////////////////////////////////////////////////////////////////////////////////
I want somthing like this: keep 2 getxcontroller working even if the app detached
//////////////////////////////////////////////////////////////////////////////////////////
await Firebase.initializeApp(
name: 'firebase',
options: const FirebaseOptions(//firebaseconfig),
).whenComplete(() {
final notifc = Get.put(Notificationsc());
final msgl = Get.put(MessageslistsController());
});
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
if (service is AndroidServiceInstance) {
service.setForegroundNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
}
// test using external plugin
final deviceInfo = DeviceInfoPlugin();
String? device;
if (Platform.isAndroid) {
final androidInfo = await deviceInfo.androidInfo;
device = androidInfo.model;
}
if (Platform.isIOS) {
final iosInfo = await deviceInfo.iosInfo;
device = iosInfo.model;
}
service.invoke(
'update',
{
"current_date": DateTime.now().toIso8601String(),
"device": device,
},
);
});
}
I am building an Android application using Flutter. My app needs to display local notification. I am using this package, https://pub.dev/packages/flutter_local_notifications. When I show the notification on the emulator it is working. But it is not working, when I compiled the release APK and installed it on the actual device.
This is NotificationService class
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationService
{
static FlutterLocalNotificationsPlugin? flip;
static FlutterLocalNotificationsPlugin getFlipInstance()
{
if (flip == null) {
flip = FlutterLocalNotificationsPlugin();
// app_icon needs to be a added as a drawable
// resource to the Android head project.
var android = const AndroidInitializationSettings('#mipmap/ic_launcher');
var ios = const IOSInitializationSettings();
var settings = InitializationSettings(android: android, iOS: ios);
flip!.initialize(settings);
}
return flip as FlutterLocalNotificationsPlugin;
}
static Future showNotification(String title, String body) async {
var androidPlatformChannelSpecifics = const AndroidNotificationDetails("your channel id", "my channel name");
var iOSPlatformChannelSpecifics = const IOSNotificationDetails();
// initialise channel platform for both Android and iOS device.
var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);
await getFlipInstance().show(0, title,
body,
platformChannelSpecifics, payload: 'Default_Sound'
);
}
}
I show notification like this in the initState method of home page.
#override
void initState() {
super.initState();
setState(() {
NotificationService.showNotification("Local Notification", "Local Notification Message");
}
As I mentioned, it works on the emulator. But when I generated an APK and installed it on the real device, it is not working.
I am working on a food delivery app with Flutter. I have recently Implemented the flutter_local_notifications and the notification is working fine. But there's one problem is that the notification doesn't show as pop up by default. The "Show as pop up" option is disabled by default in the notification settings.
Is there any way that when the app is installed the "Show as pop up" option is enabled by default.
Here's my Notification Configuration Code:
void registerNotification() {
// This function registers the user for recieving push notifications.
// After registering the user, it creates a new field inside 'userForChat' Database
// The field is called : 'pushToken' which is later used on to configure Firebase Automatic Cloud Messaging
firebaseMessaging.requestNotificationPermissions();
firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
print('onMessage: $message');
Platform.isAndroid
? showNotification(message['notification'])
: showNotification(message['aps']['alert']);
return;
},
onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
},
onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
return;
},
);
// Token for Firebase Messaging
firebaseMessaging.getToken().then((token) {
print('token: $token');
Firestore.instance
.collection('usersForChat')
.document(currentUserId)
.updateData(
{'pushToken': token}); //Sets the firebase Token into the database
}).catchError((onError) {
setState(() {});
});
}
void configLocalNotification() {
var initializationSettingsAndroid = AndroidInitializationSettings(
'mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
void showNotification(message) async {
// This function takes the notfication message as input triggers the notification to show the message.
// The input is in a json format so you have to decode the json with dart:convert.
// IMPORTANT: Specify the Application package name according to the OS.
//For Android, Use the android app package name from firebase
//For iOS, Use the iOS app package name from firebase
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
// add your apps package name for each OS(Android:iOS)
Platform.isAndroid
? 'com.jexmovers.app' //Update the package name to your app's package names
: 'com.jexmovers.ios', //Update the package name to your app's package names
'JexMovers Chat',
'App that lets you contact with your food delivery person',
playSound: true,
enableVibration: true,
importance: Importance.Max,
priority: Priority.Max,
visibility: NotificationVisibility.Public,
enableLights: true,
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
print(message);
print(message['body'].toString());
print(json.encode(message));
await flutterLocalNotificationsPlugin.show(
0,
message['title'].toString(),
message['body'].toString(),
platformChannelSpecifics,
payload: json.encode(message),
);
}
I need to show firebase notifications when the app is on foreground by using local notification but it is not working.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin=new FlutterLocalNotificationsPlugin();
static FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
static StreamController<Map<String, dynamic>> _onMessageStreamController =
StreamController.broadcast();
static StreamController<Map<String, dynamic>> _streamController =
StreamController.broadcast();
static final Stream<Map<String, dynamic>> onFcmMessage =
_streamController.stream;
#override
void initState() {
super.initState();
var android=AndroidInitializationSettings('mipmap/ic_launcher.png');
var ios=IOSInitializationSettings();
var platform=new InitializationSettings(android,ios);
flutterLocalNotificationsPlugin.initialize(platform);
firebaseCloudMessaging_Listeners();
}
Here is the Firebase Code
void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();
_firebaseMessaging.getToken().then((token) {
print("FCM TOKEN--" + token);
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
showNotification(message);
},
onResume: (Map<String, dynamic> message) async {
print('on resume $message');
},
onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
},
);
}
This is showNotification method
void showNotification(Map<String, dynamic> msg) async{
print(msg);
var android = new AndroidNotificationDetails(
'my_package', 'my_organization', 'notification_channel', importance: Importance.Max, priority: Priority.High);
var iOS = new IOSNotificationDetails();
var platform=new NotificationDetails(android, iOS);
await flutterLocalNotificationsPlugin.show(
0,'My title', 'This is my custom Notification', platform,);
}
and Firebase Response
{notification: {title: Test Title, body: Test Notification Text}, data: {orderid: 2, click_action: FLUTTER_NOTIFICATION_CLICK, order name: farhana}}
You can find the answer in FlutterFire documentation
https://firebase.flutter.dev/docs/migration/#messaging
You just add to your code the following line
FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(alert: true, badge: true, sound: true);
There is an active issue logged on GitHub repository for the package regarding the same. Firebase messaging and local notifications won't work together on iOS since you can register only a single delegate for notifications.
Check out: https://github.com/MaikuB/flutter_local_notifications/issues/111
There's also an active flutter issue for the same:
https://github.com/flutter/flutter/issues/22099
Problem:
See the Push Notification while application is in foreground.
Solution:
I was using firebase_message plugin and I was able to see the Push Notification while application is in foreground by making these few changes in my flutter project's iOS AppDelegate.swift file in flutter project.
import UIKit
import Flutter
import UserNotifications
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate, UNUserNotificationCenterDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// set the delegate in didFinishLaunchingWithOptions
UNUserNotificationCenter.current().delegate = self
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
// This method will be called when app received push notifications in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .badge, .sound])
}
}
Note:
This also works while using with flutter_local_notification plugin but with an issue that onSelectNotification is not working due to changes done above.
For not receiving the notification in foreground make sure the android drawable file contains the launcher_icon or the icon which you have set in shownotification function.
I also couldn't get firebase notifications with flutter_local_notifications working on iOS in foreground. Background notifications worked fine. Problem was that firebase notification data is different on iOS. Notification data is not ["notification"]["title"] as in android but ["aps"]["alert"]["title"].