can anyone show me with code that how can I schedule the notification in flutter using local notification plugin.
Tried the example in git repository buy it doesn't work for me, although a normal notification is working but how can i schedule it for a specific time like a reminder?
From the plugin sample code if you wanna schedule a notification you have to use a code like that:
/// Schedules a notification that specifies a different icon, sound and vibration pattern
Future _scheduleNotification() async {
var scheduledNotificationDateTime =
new DateTime.now().add(new Duration(seconds: 5));
var vibrationPattern = new Int64List(4);
vibrationPattern[0] = 0;
vibrationPattern[1] = 1000;
vibrationPattern[2] = 5000;
vibrationPattern[3] = 2000;
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'your other channel id',
'your other channel name',
'your other channel description',
icon: 'secondary_icon',
sound: 'slow_spring_board',
largeIcon: 'sample_large_icon',
largeIconBitmapSource: BitmapSource.Drawable,
vibrationPattern: vibrationPattern,
color: const Color.fromARGB(255, 255, 0, 0));
var iOSPlatformChannelSpecifics =
new IOSNotificationDetails(sound: "slow_spring_board.aiff");
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
0,
'scheduled title',
'scheduled body',
scheduledNotificationDateTime,
platformChannelSpecifics);
}
The part you must focus is that:
// Schedule a notification in 5 secs from now
var scheduledNotificationDateTime =
new DateTime.now().add(new Duration(seconds: 5));
I suggest you to clone the plugin repo and try its example if you are not sure about the native projects setup to do in order to have your notifications to be shown.
/// IMPORTANT: running the following code on its own won't work as
there is setup required for each platform head project.
/// Please
download the complete example app from the GitHub repository where all
the setup has been done
const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails('repeating channel id','repeating channel name', 'repeating description');
const NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.periodicallyShow(0, 'repeating title', 'repeating body', RepeatInterval.everyMinute, platformChannelSpecifics, androidAllowWhileIdle: true);
you can use periodicallyShow flutter_local_notifications
Related
How can I schedule a monthly or weekly notification in flutter? The purpose is for it to act as a reminder for the user about something...
here is my code
void showMonthlyAtDayTime() async {
//var scheduledNotificationDateTime = DateTime.now().add(Duration(seconds: 10));
var time = Time(12, 6, 0);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'alarm_notif',
'Scheduled notification', // name of the notif channel
'A scheduled notification', // description of the notif channel
icon: 'question',
largeIcon: DrawableResourceAndroidBitmap('question'),
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true);
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.showMonthlyAtDayTime(
0,
'Title',
'Body',
Day.Tuesday,
time,
platformChannelSpecifics);
}
The code has (red) underline beneath the showMonthlyAtDayTime in the
'wait flutterLocalNotificationsPlugin.showMonthlyAtDayTime' line
and the 'Day.Tuesday' line...
How should I modify the above code? so that the user will get notification once per each month of every year about something.
Some methods have been removed in the latest versions.
This is the code I found to repeat a notification weekly using flutter_local_notifications.
Future<void> _scheduleWeeklyTenAMNotification() async {
await notificationsPlugin.zonedSchedule(
0,
'weekly scheduled notification title',
'weekly scheduled notification body',
_nextInstanceOfTenAM(),
const NotificationDetails(
android: AndroidNotificationDetails(
'weekly notification channel id',
'weekly notification channel name',
'weekly notificationdescription'),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.dayOfWeekAndTime);
}
tz.TZDateTime _nextInstanceOfTenAM() {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduledDate =
tz.TZDateTime(tz.local, now.year, now.month, now.day, 10);
if (scheduledDate.isBefore(now)) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}
this code is copied from the example app provided by https://pub.dev/packages/flutter_local_notifications
here is the git hub link click Here
I use a notifications that repeat every hour with different id and channel , but i got just the first one evert time and other blocked and sometimes lastone only.
this is my notification function
Future<void> _scheduleNotification(id,duration,channelname,channelid,soundandroid,soundios,message,title) async {
var vibrationPattern = Int64List(4);
vibrationPattern[0] = 0;
vibrationPattern[1] = 1000;
vibrationPattern[2] = 5000;
vibrationPattern[3] = 2000;
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
channelid,
channelname,
'your other channel description',
icon: '#mipmap/ic_launcher',
importance: Importance.Max,
priority: Priority.High,
ongoing: true,
autoCancel: false,
sound: RawResourceAndroidNotificationSound(soundandroid),
largeIcon: DrawableResourceAndroidBitmap('#mipmap/ic_launcher'),
vibrationPattern: vibrationPattern,
enableLights: true,
color: const Color.fromARGB(255, 255, 0, 0),
ledColor: const Color.fromARGB(255, 255, 0, 0),
ledOnMs: 1000,
ledOffMs: 500);
var iOSPlatformChannelSpecifics =
IOSNotificationDetails(sound:soundios);
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.periodicallyShow(
id,
title,
message,
RepeatInterval.Hourly,
platformChannelSpecifics,
);
}
and I call this function to be executed
Future<void> smartnotificationcall(channelname,id)
async{
if(channelname=="clean"){ Duration(seconds:5); return _scheduleNotification(1,20,'clean',"clean","clean","clean.wav",'test','test');}
if(channelname=="sport"){ Duration(seconds:20); return _scheduleNotification(2,30,"sport","sport","sport","sport.wav",'test','test');}
if(channelname=="eat"){ Duration(seconds:40); return _scheduleNotification(3,30,"eat","eat","eat","eat.wav",'test','test');}
if(channelname=="getout"){ Duration(seconds:50); return _scheduleNotification(4,30,"getout","getout","getout","getout.wav",'test','test');
}
}
Which platform do you use? Android uses AlarmManager to schedule repeating notifications and they are inexact and this is documented Android behaviour.
Is there any simple way to show notification in Flutter? I have already tried using this plugin:
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
NotificationAppLaunchDetails notificationAppLaunchDetails;
Future<void> _showNotification(String msg) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'696969', 'FCPN', 'FCPN Example',
importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, 'plain title', msg, platformChannelSpecifics,
payload: 'item x');
}
but I have got null pointer
For iOS, you have to configure your Xcode files.
Add the following lines to the didFinishLaunchingWithOptions method in the AppDelegate.m/AppDelegate.swift file of your iOS project
Look at the Readme for flutter_local_notifications on pub.dev for more info.
In flutter i'm using adhara_socket_io to open a socket and receive data from my server to push a notification using flutter_local_notifications and it works when the app is running, now i need to make this run in the background so when my app is not running it still receives data from my server and pushes notifications, is there anyway for doing that in flutter ?
void initSocket() async {
final deviceInfo = await Constants.getDeviceDetails();
final String deviceId = deviceInfo[2];
Uuid uuid = Uuid();
print(deviceInfo);
final id = uuid.v5(Uuid.NAMESPACE_URL, deviceId);
print('id ' + id);
SocketIOManager manager = SocketIOManager();
SocketIO socket = await manager.createInstance(
SocketOptions(URI,
enableLogging: false,
transports: [Transports.WEB_SOCKET /*, Transports.POLLING*/]),
);
socket.onConnect((data) {
print("connected...");
print(data);
socket.emit('settings', [
{'device_id': id}
]);
});
socket.onConnectError((_) => print('connect error'));
socket.onConnectTimeout((_) => print('timeout'));
socket.onError((_) => print('error'));
socket.onDisconnect((_) => print('disconnect'));
socket.on('notif', (data) {
print('notif');
_showNotificationWithDefaultSound(data['heading'],data['content']);
});
socket.connect();
}
initNotifications() {
var initializationSettingsAndroid = AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(initializationSettingsAndroid,initializationSettingsIOS);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings,onSelectNotification: onSelectNotification);
}
Future onSelectNotification(String payload)async{
print('payload');
}
Future _showNotificationWithDefaultSound(heading,content) async {
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max, priority: Priority.High);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
heading,
content,
platformChannelSpecifics,
payload: 'Default_Sound',
);
}
https://medium.com/vrt-digital-studio/flutter-workmanager-81e0cfbd6f6e
hope this will help or u can use fcm https://fireship.io/lessons/flutter-push-notifications-fcm-guide/
however i am begginer .i dont know about this too much ..sorry if this doesnt help you.
Flutter isolates using the flutter isolate package do not show notificaitons when the app has been killed.
Tried using the isolate package with dart:isolate, that does not work.
import 'dart:async';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:flutter_isolate/flutter_isolate.dart';
'package:flutter_local_notifications/flutter_local_notifications.dart';
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
}
void isolated(String args) async {
Timer.periodic(new Duration(seconds: 10), (Timer t) => print('hi!'));
Timer.periodic(new Duration(seconds: 10), (Timer y) async
{
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max,
priority: Priority.High,
ticker: 'ticker');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, 'plain title', 'plain body', platformChannelSpecifics,
payload: 'item x');
});
}
void main() async {
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
// If you have skipped STEP 3 then change app_icon to #mipmap/ic_launcher
var initializationSettingsAndroid =
new AndroidInitializationSettings('appicon');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
isolated("hi");
}
The code above is what the system sees when the app has been killed as the state classes have terminated, and no longer exist. If we can get the code above running then the isolate will still work when the app has been killed by the user in Android and iOS and the state classes are no longer there.
Thanks in advance.
Rob.
Yeah it can't be done in Flutter alone as the isolates are spawned by the parent process and they get killed when the app is terminated.
for Android use services which get spawned and persist after the app dies.
For iOS you can run a background thread which gets spawned after a minimum amount of time, but there's no guarantee as to when that will run. You can, at Apple's discretion, run apps as audio or location based, which will allow the background thread to run continuously.