Generate Flutter Local Notification when background FCM Triggers - flutter

Basically I am trying to make a notification when FCM onBackgroundMessage Triggers.
While doing this I am getting a NullPointerException at the .show(..) method of FlutterLocalNotification Plugin.
Here is my Code:
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
},
onBackgroundMessage: messageHandle,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
Future<dynamic> messageHandle(Map<String, dynamic> message) async{
if (message.containsKey("data")) {
Map data = message['data'];
String topic;
if (data.containsKey("topic")) topic = data['topic'];
if (topic == "VendorNewTrips") {
String amount = data['amount'];
String vehicle = data['vehicle'];
String tripType = data['tripType'];
String pickUpDate= data['pickUpDate'];
String pickUpTime = data['pickUpTime'];
String locations= data['locations'];
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();
new AndroidInitializationSettings('app_icon');
var bigTextStyleInformation = BigTextStyleInformation(
'Locations: <b>${locations.replaceAll("\$", " to ")}</b><br>Vehicle: <b>$vehicle</b><br>Trip Type: <b>$tripType</b><br>Pick-Up Date: <b>$pickUpDate</b><br>Pick-Up Time: <b>$pickUpTime</b>',
htmlFormatBigText: true,
contentTitle: 'Amount:- <b>Rs $amount</b>',
htmlFormatContentTitle: true,
summaryText: 'Trip Details',
htmlFormatSummaryText: true);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'1687497218170948721x8',
'New Trips Notification ',
'Notification Channel for vendor. All the new trips notifications will arrive here.',
style: AndroidNotificationStyle.BigText,
styleInformation: bigTextStyleInformation);
var platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, null);
flutterLocalNotificationsPlugin.show(5, 'Let\'s Get Wride!',
'You Have Got A New Trip!', platformChannelSpecifics,);
}
}
return null;
}
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:208)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:180)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:693)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:785)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:714)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:231)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:93)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:642)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at android.os.Looper.loop(Looper.java:190)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at android.app.ActivityThread.main(ActivityThread.java:7211)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)
E/flutter (15092): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (15092): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (15092): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter (15092): <asynchronous suspension>
E/flutter (15092): #2 AndroidFlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:135:21)
E/flutter (15092): #3 FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:93:13)
E/flutter (15092): #4 messageHandle (package:wride/SplashScreen/SplashScreen.dart:155:39)
E/flutter (15092): #5 _fcmSetupBackgroundChannel.<anonymous closure> (package:firebase_messaging/firebase_messaging.dart:38:30)
E/flutter (15092): #6 MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:402:55)
E/flutter (15092): #7 MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_channel.dart:370:54)
E/flutter (15092): #8 _DefaultBinaryMessenger.handlePlatformMessage (package:flutter/src/services/binding.dart:200:33)
E/flutter (15092): #9 _invoke3.<anonymous closure> (dart:ui/hooks.dart:303:15)
E/flutter (15092): #10 _rootRun (dart:async/zone.dart:1126:13)
E/flutter (15092): #11 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (15092): #12 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (15092): #13 _invoke3 (dart:ui/hooks.dart:302:10)
E/flutter (15092): #14 _dispatchPlatformMessage (dart:ui/hooks.dart:162:5)
E/flutter (15092):
I want to make my own stylish notification when background message triggers because FCM doesnot support Notification Styles.
Please Help!
Edit: I looked into the plugin FlutterLocalNotification and came to know that the NotificationDetails.java Line 151 Interger iconResourceID is null all the time. I don't know what to do now.

Okay, I got to know where is the mistake. I forgot to initialize the flutter local notification plugin with the app_icon. I changed my messageHandle method and it is working now.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'1687497218170948721x8',
'New Trips Notification ',
'Notification Channel for vendor. All the new trips notifications will arrive here.',
style: AndroidNotificationStyle.BigText,
icon: "app_icon",
styleInformation: BigTextStyleInformation(
"hanji hogya?",// 'Locations: <b>${locations.replaceAll("\$", " to ")}</b><br>Vehicle: <b>$vehicle</b><br>Trip Type: <b>$tripType</b><br>Pick-Up Date: <b>$pickUpDate</b><br>Pick-Up Time: <b>$pickUpTime</b>',
htmlFormatBigText: true,
contentTitle: 'Amount:- <b>Rs 22000000</b>',
htmlFormatContentTitle: true,
summaryText: 'Trip Details',
htmlFormatSummaryText: true));

Related

Unhandled Exception: setState() called after dispose()

I am trying to receive notifications in my flutter app using Firebase Messaging to display them in the app, but I keep getting the error:
/FLTFireMsgReceiver( 6823): broadcast received for message
E/flutter ( 6823): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called after dispose(): _TipsState#aa4df(lifecycle state: defunct, not mounted)
E/flutter ( 6823): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 6823): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 6823): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 6823): #0 State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1085:9)
E/flutter ( 6823): #1 State.setState (package:flutter/src/widgets/framework.dart:1120:6)
E/flutter ( 6823): #2 _TipsState.getNotification.<anonymous closure> (package:stock_baba/Screens/Tips.dart:38:9)
E/flutter ( 6823): #3 _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 6823): #4 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 6823): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 6823): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter ( 6823): #7 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter ( 6823): #8 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter ( 6823): #9 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter ( 6823): #10 _rootRun (dart:async/zone.dart:1418:47)
E/flutter ( 6823): #11 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 6823): #12 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 6823): #13 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 6823): #14 _rootRun (dart:async/zone.dart:1426:13)
E/flutter ( 6823): #15 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 6823): #16 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 6823): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 6823): #18 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 6823): #19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
The PushNotification class is a simple class with the string fields title, body, dataTitle and dataBody.
My code is as follows:
class _TipsState extends State<Tips> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
final List<PushNotification> messages = [];
PushNotification? _notificationInfo;
#override
void initState() {
getNotification();
super.initState();
}
void getNotification() async {
NotificationSettings settings =
await _firebaseMessaging.requestPermission();
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print("Permission granted!");
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
dataTitle: message.data['title'],
dataBody: message.data['body']);
setState(() {
_notificationInfo = notification;
});
if (notification != null) {
showSimpleNotification(Text(_notificationInfo!.title!),
duration: Duration(seconds: 2),
subtitle: Text(_notificationInfo!.body!));
}
print(notification);
print(message.data);
});
} else {
print("Permission declined!");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: messages.isEmpty
? Container()
: ListView(
children: [Text(messages[0].title!)],
),
);
}
}
I tried wrapping my setState() with mounted() but it didn't work.
How can I resolve this issue and display the incoming notifications in my app?
Cancel the Stream after dispose it
Create StreamSubscription variable
StreamSubscription messagingSubscription;
Assign variable to your listen
....
messagingSubscription = FirebaseMessaging.onMessage.listen((RemoteMessage message) {
Dispose your StreamSubscription
#override
void dispose() {
messagingSubscription?.cancel();
super.dispose();
}
here is my code and its in working ..copy the code and make a dart class and paste it . your notification start working
use there plugins
firebase_core: ^1.11.0
firebase_messaging: ^11.2.5
flutter_local_notifications: ^9.2.0
import 'dart:convert';
import 'dart:math';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:vcare/firebase_options.dart';
class NotificationHelper {
NotificationDetails get _ongoing {
const androidChannelSpecifics = AndroidNotificationDetails(
'customer-channel-id',
'customer-channel-name',
importance: Importance.max,
priority: Priority.high,
ongoing: false,
autoCancel: true,
);
const iOSChannelSpecifics = IOSNotificationDetails();
return const NotificationDetails(android: androidChannelSpecifics, iOS: iOSChannelSpecifics);
}
// Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
// await initFirebase();
// }
configure() async {
await initFirebase();
FirebaseMessaging messaging = FirebaseMessaging.instance;
await requestPermission(messaging);
final String? token = await messaging.getToken();
// FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
final notification = await setupLocalNotification();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
showNotification(
notification,
title: message.notification?.title,
body: message.notification?.body,
payload: message.data,
type: _ongoing,
);
});
return token;
}
Future<void> requestPermission(FirebaseMessaging messaging) async {
await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
}
Future<void> initFirebase() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
}
setupLocalNotification() async {
const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings(
'notification_icon',
);
final IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: (int id, String? title, String? body, String? payload) {},
);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
var notification = FlutterLocalNotificationsPlugin();
await notification.initialize(initializationSettings, onSelectNotification: (_) {});
return notification;
}
showNotification(FlutterLocalNotificationsPlugin notifications,
{required String? title, required String? body, required NotificationDetails type, required payload}) {
notifications.show(Random().nextInt(100), title, body, type, payload: json.encode(payload ?? {}));
}
}
and then call this class in main.dart file here is the code
WidgetsFlutterBinding.ensureInitialized();
String? token = await NotificationHelper().configure();
_storeFCMToken(token);
print("deviceToken $token");
if you find any problem please let me know. if you find this code is helping you .then please mark my answer as accepted

Why flutter local notifications give exceptions

I'm trying to send a notification with flutter on android using this dependency:
"flutter_local_notifications: ^9.0.1"
But it gives me this error when I click the button "test".
Anyone has an idea how can I solve it?
////////////////////////////////////////////////////////////////////////
In main.dart:
ElevatedButton(
onPressed: () => NotificationApi.showNotification(
title: 'Samira', body: 'Heyy theree !!!', payload: 'samira'),
child: Text("test"),
In notification.dart:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static Future _notificationDetails() async {
return const NotificationDetails(
android: AndroidNotificationDetails(
'channel id',
'channel name',
channelDescription: 'channel description',
importance: Importance.max,
),
//iOS: IOSNotificationDetails(),
);
}
static Future showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async =>
_notifications.show(
id,
title,
body,
await _notificationDetails(),
payload: payload,
);
}
The error in my console:
Performing hot reload...
Syncing files to device Android SDK built for x86...
Reloaded 1 of 1023 libraries in 426ms.
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:238)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:180)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:793)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1056)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:949)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:84)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:872)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at android.os.MessageQueue.next(MessageQueue.java:323)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at android.os.Looper.loop(Looper.java:136)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at android.app.ActivityThread.main(ActivityThread.java:6077)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
E/MethodChannel#dexterous.com/flutter/local_notifications(15565): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
E/flutter (15565): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null, java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/flutter (15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:238)
E/flutter (15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:180)
E/flutter (15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:793)
E/flutter (15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1056)
E/flutter (15565): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:949)
E/flutter (15565): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/flutter (15565): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:84)
E/flutter (15565): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:872)
E/flutter (15565): at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (15565): at android.os.MessageQueue.next(MessageQueue.java:323)
E/flutter (15565): at android.os.Looper.loop(Looper.java:136)
E/flutter (15565): at android.app.ActivityThread.main(ActivityThread.java:6077)
E/flutter (15565): at java.lang.reflect.Method.invoke(Native Method)
E/flutter (15565): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
E/flutter (15565): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
E/flutter (15565): )
E/flutter (15565): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (15565): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
E/flutter (15565): <asynchronous suspension>
E/flutter (15565): #2 FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:194:7)
E/flutter (15565): <asynchronous suspension>
E/flutter (15565):
You should add the notification icon properly. It solved my issue.
static Future _notificationDetails() async {
return const NotificationDetails(
android: AndroidNotificationDetails(
'channel id',
'channel name',
channelDescription: 'channel description',
importance: Importance.max,
icon: "ic_notification", //<-- Add this parameter
),
//iOS: IOSNotificationDetails(),
);
}

Null Check operator used on a null value on flutter with Sqflite

I'm studying flutter with Sqflite and trying to make a small app, but I'm getting this error when I run the code, I've looked literaly everywhere to findout what it could be.
Here the code code who use the Sqflite package:
Future<Database> getDatabase() async {
final String path = join(await getDatabasesPath(), 'bytebank.db');
return openDatabase(path, onCreate: (db, version) {
db.execute('CREATE TABLE contacts'
'(id INTEGER PRIMARY KEY, '
'name TEXT, '
'account_number INTEGER)');
}, version: 1);
}
Future<int> save(Contact contact) async {
final Database db = await getDatabase();
final Map<String, dynamic> contactMap = Map();
contactMap['name'] = contact.name;
contactMap['account_number'] = contact.account;
contactMap['id'] = contact.id;
return db.insert('contacts', contactMap);
}
Future<List<Contact>> findAll() async {
final Database db = await getDatabase();
final List<Map<String, dynamic>> result = await db.query('contacts');
final List<Contact> contacts = [];
for (Map<String, dynamic> row in result) {
final Contact contact = Contact(
row['id'],
row['name'],
row['account_number'],
);
contacts.add(contact);
}
return contacts;
}
And here is the only one place where I use This functions:
void main() {
save(Contact('William', 2, 13456)).then((id) {
findAll().then((contacts) => print(contacts));
});
runApp(ByteBankApp());
}
Model Class:
class Contact {
final String name;
final int account;
final int id;
Contact( this.id,
this.name,
this.account,
);
#override
String toString() {
return 'Contact{name: $name, account: $account}';
}
}
Error Trace back:
Launching lib\main.dart on sdk gphone x86 arm in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:52296/07rtnvW9tlQ=/ws
Syncing files to device sdk gphone x86 arm...
E/flutter (28649): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (28649): #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
E/flutter (28649): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
E/flutter (28649): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
E/flutter (28649): #3 invokeMethod (package:sqflite/src/sqflite_impl.dart:17:13)
E/flutter (28649): #4 SqfliteDatabaseFactoryImpl.invokeMethod (package:sqflite/src/factory_impl.dart:82:7)
E/flutter (28649): #5 SqfliteDatabaseFactoryMixin.safeInvokeMethod.<anonymous closure> (package:sqflite_common/src/factory_mixin.dart:41:38)
E/flutter (28649): #6 wrapDatabaseException (package:sqflite/src/exception_impl.dart:7:32)
E/flutter (28649): #7 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:78:7)
E/flutter (28649): #8 SqfliteDatabaseFactoryMixin.safeInvokeMethod (package:sqflite_common/src/factory_mixin.dart:41:7)
E/flutter (28649): #9 SqfliteDatabaseFactoryMixin.getDatabasesPath (package:sqflite_common/src/factory_mixin.dart:153:26)
E/flutter (28649): #10 getDatabasesPath (package:sqflite/sqflite.dart:161:54)
E/flutter (28649): #11 getDatabase (package:bytebank/database/app_database.dart:6:34)
E/flutter (28649): #12 save (package:bytebank/database/app_database.dart:16:29)
E/flutter (28649): #13 main (package:bytebank/main.dart:7:3)
E/flutter (28649): #14 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (28649): #15 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (28649): #16 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (28649): #17 _runZoned (dart:async/zone.dart:1789:10)
E/flutter (28649): #18 runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (28649): #19 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (28649): #20 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (28649): #21 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (28649):
I am not sure if will help, but I was running into a similar issue when initializing a database in an async "main" method. Adding the following:
WidgetsFlutterBinding.ensureInitialized();
inside the method before the code initializing the database solved the problem.

Flutter show local notifications at exact time using workmanager

I want to set the local notification in flutter (android app), I got to know about workmanager package but I don't know how to use it for my purpose. I want to send notifications at the exact time which is selected by the user.
Time Selection:
Container(
padding: EdgeInsets.all(15),
child: IconButton(icon: Icon(Icons.alarm, color: Colors.white, size: 70,),
onPressed: (){
DatePicker.showTimePicker(context,
theme: DatePickerTheme(
containerHeight: 210.0,
),
showTitleActions: true, onConfirm: (time) {
ttime = '${time.hour} : ${time.minute} : ${time.second}';
//print(_time);
_setNotifyTime();
setState(() {});
}, currentTime: DateTime.now(), locale: LocaleType.en);
setState(() {});
}),
),
Saving this time in sharedpreferences:
Future<void> _setNotifyTime() async{
final prefs = await SharedPreferences.getInstance();
final savedNotifyTime = await _getStringFromSharedPrefs();
await prefs.setString('notificationTime', ttime);
//print("this $savedNotifyTime");
return savedNotifyTime;
}
Getting this time from shared preferences:
Future<String> _getStringFromSharedPrefs() async{
final prefs = await SharedPreferences.getInstance();
notifyTime = prefs.getString('notificationTime');
return notifyTime;
}
Flutter local notification as per selected time:
Future<void> showDailyAtTime() async {
var splited = notifyTime.split(':');
int hour = int.parse(splited[0]);
int minute = int.parse(splited[1]);
int second = int.parse(splited[2]);
print(hour.toString());
print(minute.toString());
print(second.toString());
var reviewTime = Time(hour, minute, second);
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 2',
'CHANNEL_NAME 2',
"CHANNEL_DESCRIPTION 2",
importance: Importance.max,
priority: Priority.high,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(android: androidChannelSpecifics, iOS: iosChannelSpecifics);
await flutterLocalNotificationsPlugin.showDailyAtTime(
0,
'Title at ${reviewTime.hour}:${reviewTime.minute}.${reviewTime.second}',
'Test Body', //null
reviewTime,
platformChannelSpecifics,
payload: 'Test Payload',
);
}
Workmanager implementation:
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData) async {
notificationPlugin.showDailyAtTime();
return Future.value(true);
});
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Workmanager().initialize(callbackDispatcher);
await Workmanager().registerPeriodicTask("test_workertask", "test_workertask",
inputData: {"data1": "value1", "data2": "value2"},
frequency: Duration(minutes: 15),
initialDelay: Duration(minutes: 15));
runApp(MyApp());
}
This is working when I am calling it from a button in-app but as soon as I go in the background it doesn't work.
It is giving the following error, when I implement the above code:
HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2
D/EGL_emulation( 6089): eglMakeCurrent: 0xe90561a0: ver 2 0 (tinfo 0xe0eadb70)
E/flutter ( 6089): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'split' was called on null.
E/flutter ( 6089): Receiver: null
E/flutter ( 6089): Tried calling: split(":")
E/flutter ( 6089): #0 Object.noSuchMethod (dart:core- patch/object_patch.dart:54:5)
E/flutter ( 6089): #1 NotificationPlugin.showDailyAtTime (package:finance_manager/widgets/NotificationPlugin.dart:107:30)
E/flutter ( 6089): #2 callbackDispatcher.<anonymous closure> (package:finance_manager/main.dart:14:24)
E/flutter ( 6089): #3 callbackDispatcher.<anonymous closure> (package:finance_manager/main.dart:12:29)
E/flutter ( 6089): #4 Workmanager.executeTask.<anonymous closure> (package:workmanager/src/workmanager.dart:89:28)
E/flutter ( 6089): #5 Workmanager.executeTask.<anonymous closure> (package:workmanager/src/workmanager.dart:87:45)
E/flutter ( 6089): #6 MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:435:55)
E/flutter ( 6089): #7 MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_channel.dart:382:34)
E/flutter ( 6089): #8 _DefaultBinaryMessenger.handlePlatformMessage (package:flutter/src/services/binding.dart:284:33)
E/flutter ( 6089): #9 _invoke3.<anonymous closure> (dart:ui/hooks.dart:221:15)
E/flutter ( 6089): #10 _rootRun (dart:async/zone.dart:1354:13)
E/flutter ( 6089): #11 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter ( 6089): #12 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter ( 6089): #13 _invoke3 (dart:ui/hooks.dart:220:10)
E/flutter ( 6089): #14 PlatformDispatcher._dispatchPlatformMessage (dart:ui/platform_dispatcher.dart:457:7)
E/flutter ( 6089): #15 _dispatchPlatformMessage (dart:ui/hooks.dart:90:31)
E/flutter ( 6089):
I/WM-WorkerWrapper( 6089): Worker result SUCCESS for Work [ id=87272c98-d905-4b69-a1ce-86c13336ab8b, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
Please help me.
Thanks for your replies in advance.

Error displaying local notifications in Flutter

I am using the flutter_local_notifications plugin and the default boilerplate app.
This is the code that I'm using-
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
void main() async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
// added boat.png in the drawables folder
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('boat.png');
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: null,
macOS: null,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: selectNotification);
void showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.max,
priority: Priority.high,
showWhen: false);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, 'plain title', 'plain body', platformChannelSpecifics,
payload: 'item x');
}
showNotification();
runApp(MyApp());
}
Future selectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: $payload');
}
// Modified the example code - it navigated to a different screen. I am just printing the payload
print(payload);
}
Note - I am using the plugin exclusively for android apps. So, I haven't configured it for iOS or macOS.
I suspect that I am not using the plugin properly. But I followed all the instructions on the plugin's website.
I got this error message -
E/flutter ( 5446): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 5446): #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
E/flutter ( 5446): #1 MethodChannel.setMethodCallHandler (package:flutter/src/services/platform_channel.dart:378:5)
E/flutter ( 5446): #2 AndroidFlutterLocalNotificationsPlugin.initialize (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:84:14)
E/flutter ( 5446): #3 FlutterLocalNotificationsPlugin.initialize (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:120:13)
E/flutter ( 5446): #4 main (package:desktop_test/main.dart:16:41)
E/flutter ( 5446): #5 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:146:25)
E/flutter ( 5446): #6 _rootRun (dart:async/zone.dart:1354:13)
E/flutter ( 5446): #7 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter ( 5446): #8 _runZoned (dart:async/zone.dart:1789:10)
E/flutter ( 5446): #9 runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter ( 5446): #10 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:139:5)
E/flutter ( 5446): #11 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter ( 5446): #12 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter ( 5446):