Flutter show local notifications at exact time using workmanager - flutter

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.

Related

'instanceFactory != null': Object/factory with type UserController is not registered inside GetIt. (But it is)

I have a two apps project, I am using get_it to get the profile picture from firebase Storage
.
The problem is that in the first app the code is working perfectly and the sign in procedure finish up normally, but in this one I copied the code as it was and made the necessary changes (imports mostly) however getting the profile picture using get_it is interrupting the signing and the sign up procedure and returning this error in the console:
/flutter ( 4798): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: 'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7: 'instanceFactory != null': Object/factory with type UserController is not registered inside GetIt.
package:get_it/get_it_impl.dart:372
E/flutter ( 4798): (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
E/flutter ( 4798): Did you forget to register it?)
E/flutter ( 4798): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:51:61)
E/flutter ( 4798): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:40:5)
E/flutter ( 4798): #2 _GetItImplementation._findFactoryByNameAndType
package:get_it/get_it_impl.dart:372
E/flutter ( 4798): #3 _GetItImplementation.get
package:get_it/get_it_impl.dart:393
E/flutter ( 4798): #4 _SignInPageState.build.<anonymous closure>
package:nhafeflek/…/authentication/sign_in.dart:193
E/flutter ( 4798): #5 _SignInPageState.build.<anonymous closure>
package:nhafeflek/…/authentication/sign_in.dart:190
E/flutter ( 4798): #6 _InkResponseState._handleTap
E/flutter ( 4798): #7 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:198
E/flutter ( 4798): #8 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:613
E/flutter ( 4798): #9 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:298
E/flutter ( 4798): #10 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:232
E/flutter ( 4798): #11 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:563
E/flutter ( 4798): #12 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:94
E/flutter ( 4798): #13 PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:139
E/flutter ( 4798): #14 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:614:13)
E/flutter ( 4798): #15 PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:137
E/flutter ( 4798): #16 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:123
E/flutter ( 4798): #17 GestureBinding.handleEvent
E/flutter ( 4798): #18 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:425
E/flutter ( 4798): #19 RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:326
E/flutter ( 4798): #20 GestureBinding._handlePointerEventImmediately
package:flutter/…/gestures/binding.dart:380
E/flutter ( 4798): #21 GestureBinding.handlePointerEvent
package:flutter/…/gestures/binding.dart:344
E/flutter ( 4798): #22 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:302
E/flutter ( 4798): #23 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:285
E/flutter ( 4798): #24 _rootRunUnary (dart:async/zone.dart:1442:13)
E/flutter ( 4798): #25 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 4798): #26 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 4798): #27 _invoke1 (dart:ui/hooks.dart:170:10)
E/flutter ( 4798): #28 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
E/flutter ( 4798): #29 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
and as I already said it is registered and already working in the other app and here is my code:
My locator.dart file
import 'package:get_it/get_it.dart';
import 'package:nhafeflek/services/auth.dart';
import 'package:nhafeflek/services/storage.dart';
import 'package:nhafeflek/services/userController.dart';
var locator = GetIt.instance;
Future<void> setupServices() async {
locator.registerSingleton<AuthService>(AuthService());
locator.registerSingleton<StorageService>(StorageService());
locator.registerLazySingleton<UserController>(() => UserController());
}
My UserController.dart file:
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:nhafeflek/models/user.dart';
import 'package:nhafeflek/services/auth.dart';
import 'package:nhafeflek/services/locator.dart';
import 'package:nhafeflek/services/storage.dart';
class UserController {
late Userr _currentUser;
final AuthService _authService = locator.get<AuthService>();
final FirebaseAuth _auth = FirebaseAuth.instance;
late Future init;
final StorageService _storageService = locator.get<StorageService>();
UserController() {
init = initUser();
}
Future<Userr> initUser() async {
_currentUser = await _authService.getUser();
return _currentUser;
}
Userr get currentUser => _currentUser;
Future<void> uploadProfilePicture(File image) async {
_currentUser.avatarUrl = await _storageService.uploadFile(image);
}
Userr? _userFromFirebaseUser(User? user) {
if (user != null) {
return Userr(uid: user.uid);
} else {
return null;
}
}
Future<String> getDownloadUrl() async {
return await _storageService
.getUserProfileImageDownloadUrl(FirebaseAuth.instance.currentUser!.uid);
}
Future signInWithEmailAndPassword(String email, String password) async {
_currentUser =
await _authService.signInWithEmailAndPassword(email, password);
_currentUser = Userr(
uid: FirebaseAuth.instance.currentUser!.uid,
avatarUrl: await getDownloadUrl());
try {
UserCredential result = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User barber = result.user!;
return _userFromFirebaseUser(barber);
} catch (e) {
return null;
}
}
}
My SignIn button:
ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
dynamic result = await locator
.get<UserController>()
.signInWithEmailAndPassword(email, password);
if (result == null) {
setState(() =>
error = 'Something went wrong... Please try again!');
}
}
},
style: ButtonStyle(
shadowColor:
MaterialStateProperty.all(const Color(0xff5680a7)),
backgroundColor:
MaterialStateProperty.all(const Color(0xff5680a7)),
padding: MaterialStateProperty.all(const EdgeInsets.symmetric(horizontal: 120, vertical: 15)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
side: const BorderSide(
color: Color(0xff5680a7), width: 3)))),
child: const Text(
'Sign In',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
)
)
If you need any other sample of the code don't hesitate for asking. I seek your help.

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

Flutter - Isolate : NoSuchMethodError: The method 'toRawHandle' was called on null

Goal
I'm trying to perform real-time object detection with a Flutter app, using Tensorflow 2, with a SSD Mobilenet V2 model
I managed to get this work, using this git repo
However, I am encountering some latencies on the camera output display, so I decided to call the detection method inside a Isolate
What I've tried
The recognition method is Tflite.detectObjectOnFrame() from tflite plugin
As far as I understand, I have to use a particular Isolate in order to use plugin methods in another thread, so I'm using the isolate_handler plugin
The Code
Camera.dart
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:tflite/tflite.dart';
import 'package:isolate_handler/isolate_handler.dart';
import 'dart:math' as math;
typedef void Callback(List<dynamic> list, int h, int w);
class Camera extends StatefulWidget {
final List<CameraDescription> cameras;
final Callback setRecognitions;
Camera(this.cameras, this.setRecognitions);
#override
_CameraState createState() => new _CameraState();
}
class _CameraState extends State<Camera> {
CameraController controller;
bool isDetecting = false;
final isolates = IsolateHandler();
int startTime;
#override
void initState() {
super.initState();
if (widget.cameras == null || widget.cameras.length < 1) {
print('No camera is found');
} else {
controller = new CameraController(
widget.cameras[0],
ResolutionPreset.high,
);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
controller.startImageStream((CameraImage img) {
if (!isDetecting) {
isDetecting = true;
startTime = new DateTime.now().millisecondsSinceEpoch;
//HERE IS THE ISOLATE
isolates.spawn<List<dynamic>>(
entryPoint,
name: 'object_detection',
onInitialized: () => isolates.send(img, to: 'object_detection'));
}
}
);
});
}
}
#override
void dispose() {
controller?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
if (controller == null || !controller.value.isInitialized) {
return Container();
}
var tmp = MediaQuery.of(context).size;
var screenH = math.max(tmp.height, tmp.width);
var screenW = math.min(tmp.height, tmp.width);
tmp = controller.value.previewSize;
var previewH = math.max(tmp.height, tmp.width);
var previewW = math.min(tmp.height, tmp.width);
var screenRatio = screenH / screenW;
var previewRatio = previewH / previewW;
return OverflowBox(
maxHeight:
screenRatio > previewRatio ? screenH : screenW / previewW * previewH,
maxWidth:
screenRatio > previewRatio ? screenH / previewH * previewW : screenW,
child: CameraPreview(controller),
);
}
void entryPoint(Map<String, dynamic> context) {
final messenger = HandledIsolate.initialize(context);
messenger.listen((img) async {
// HERE IS THE METHOD I USE FROM TFLITE PLUGIN
var recognitions = Tflite.detectObjectOnFrame(
bytesList: img.planes.map((plane) {
return plane.bytes;
}).toList(),
model: "SSDMobileNet",
imageHeight: img.height,
imageWidth: img.width,
imageMean: 127.5,
imageStd: 127.5,
numResultsPerClass: 1,
threshold: 0.4,
);
messenger.send(recognitions);
});
}
void setRecognitions(List<dynamic> recognitions) {
int endTime = new DateTime.now().millisecondsSinceEpoch;
print("Detection took ${endTime - startTime}");
widget.setRecognitions(recognitions, /*img.height, img.width*/1280, 720);
isDetecting = false;
isolates.kill('object_detection');
}
}
The error I get
E/flutter ( 7960): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'toRawHandle' was called on null.
E/flutter ( 7960): Receiver: null
E/flutter ( 7960): Tried calling: toRawHandle()
E/flutter ( 7960): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 7960): #1 FlutterIsolate.spawn (package:flutter_isolate/flutter_isolate.dart:25:55)
E/flutter ( 7960): #2 HandledIsolate._init (package:isolate_handler/src/handled_isolate.dart:174:37)
E/flutter ( 7960): #3 new HandledIsolate (package:isolate_handler/src/handled_isolate.dart:108:5)
E/flutter ( 7960): #4 IsolateHandler.spawn (package:isolate_handler/isolate_handler.dart:167:22)
E/flutter ( 7960): #5 _CameraState.initState.<anonymous closure>.<anonymous closure> (package:flutter_realtime_detection/camera.dart:56:22)
E/flutter ( 7960): #6 CameraController.startImageStream.<anonymous closure> (package:camera/camera.dart:412:20)
E/flutter ( 7960): #7 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 7960): #8 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 7960): #9 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 7960): #10 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:357:11)
E/flutter ( 7960): #11 _DelayedData.perform (dart:async/stream_impl.dart:611:14)
E/flutter ( 7960): #12 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:730:11)
E/flutter ( 7960): #13 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:687:7)
E/flutter ( 7960): #14 _rootRun (dart:async/zone.dart:1182:47)
E/flutter ( 7960): #15 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 7960): #16 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 7960): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 7960): #18 _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 7960): #19 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 7960): #20 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 7960): #21 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 7960): #22 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 7960): #23 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
Any idea of what I am doing wrong ? Thank you.
Isolates don't share memory between them, which means you can only use primitive values and static/top-level functions. The entryPoint is not a static/top-level function in your case.
Check out the easy_isolate plugin, it provides an easy way to work with isolates with well-explained documentation. But doesn't call platform plugins.
https://pub.dev/packages/easy_isolate

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):

Unhandled Exception: Exception: Failed to create Register

the method name is createResgister so this is the method that returns a Future that contains a Response. ok and in there is TextEdittingController of each form i want post and the api i want to post it too
ok am having an error trying to post a register form to an apiKey code:
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:logistics_app/models/registerApi.dart';
import 'package:logistics_app/ui/dashboard_view.dart';
import 'package:logistics_app/utils/validation.dart';
import 'package:http/http.dart' as http;
import '../ui/login_view.dart';
class UserOnboardingModel extends ChangeNotifier with ValidationMixin{
TextEditingController firstController = TextEditingController();
TextEditingController lastController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController phoneController = TextEditingController();
bool showPassword = true;
final formKey = GlobalKey<FormState>();
Future<RegisterModel> _futureRegister;
Future<RegisterModel> createRegister()async{
final http.Response response = await http.post(
"apiKey",
body: jsonEncode(<String, String>{
'firstName' : validateFirstName(firstController.text),
'lastName' : validateLastName(lastController.text),
'emailAddress' : validateEmail(emailController.text),
'phoneNumber' : validatePhoneNumber(phoneController.text),
'password' : validatePassword(passwordController.text)
})
);
if(response.statusCode == 201){
return RegisterModel.fromJson(json.decode(response.body));
}else{
throw Exception('Failed to create Register');
}
}
void passRegister(){
_futureRegister = createRegister();
}
void registerForm(){
FutureBuilder<RegisterModel>(
future: _futureRegister,
builder: (context, snapshot){
if(snapshot.hasData){
return Column(
children: [
Text(snapshot.data.firstName),
Text(snapshot.data.lastName),
Text(snapshot.data.emailAddress),
Text(snapshot.data.phoneNumber),
Text(snapshot.data.password)
],
);
}else if(snapshot.hasError){
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
);
}
void togglePassword(){
showPassword = !showPassword;
notifyListeners();
}
void validateForm(){
formKey.currentState.validate();
}
void moveToLogin(context){
//go to login page
if(formKey.currentState.validate()){
Navigator.pushNamed(context, LogIn.LOG_IN_ROUTE);
}
else{
Fluttertoast.showToast(
msg: "Please Fill The Form",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 5,
backgroundColor: Colors.black,
);
}
}
void moveToDashBoardView(context){
//go to login page
if(formKey.currentState.validate()){
Navigator.push(context, MaterialPageRoute(
builder: (context) => DashboardView()
));
}
else{
Fluttertoast.showToast(
msg: "Please Fill The Form",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 5,
backgroundColor: Colors.black,
);
}
}
void moveToSignup(){
//go to sign up page
notifyListeners();
}
void moveToForgottenPassword(){
//go to forgotten password page
notifyListeners();
}
}
now this is the error am getting saying: Failed to create Register
E/flutter ( 7901): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Exception: Failed to create Register
E/flutter ( 7901): #0 UserOnboardingModel.createRegister (package:logistics_app/models/userOnboardingModel.dart:42:7)
E/flutter ( 7901): <asynchronous suspension>
E/flutter ( 7901): #1 UserOnboardingModel.passRegister (package:logistics_app/models/userOnboardingModel.dart:47:23)
E/flutter ( 7901): #2 _buildCircleAvatar.<anonymous closure>.<anonymous closure> (package:logistics_app/ui/sign_up_view.dart:241:18)
E/flutter ( 7901): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter ( 7901): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter ( 7901): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 7901): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 7901): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 7901): #8 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:256:7)
E/flutter ( 7901): #9 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:158:27)
E/flutter ( 7901): #10 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:224:20)
E/flutter ( 7901): #11 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 7901): #12 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 7901): #13 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 7901): #14 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 7901): #15 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 7901): #16 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 7901): #17 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 7901): #18 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 7901): #19 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter ( 7901):