Why am I getting errors while sending notification from firebase - flutter

The code for the app in which initializing firebase:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
// TODO: implement initState
super.initState();
FirebaseMessaging.instance.getInitialMessage();
///foreground notification
FirebaseMessaging.onMessage.listen((message) {
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
}
});
///background & opened notification
///tapped on notification
FirebaseMessaging.onMessageOpenedApp.listen((message) {
final routeFromMessage = message.data['route'];
Navigator.of(context).pushNamed(routeFromMessage);
});
}
Now if the code worked correctly, it should have navigated me to the respective routed page and printed the notification title and body in the console.
But instead I am getting errors like this:
D/FLTFireMsgReceiver( 9928): broadcast received for message
W/FLTFireMsgService( 9928): A background message could not be handled in Dart as no onBackgroundMessage handler has been registered.
W/FirebaseMessaging( 9928): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
E/flutter ( 9928): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
E/flutter ( 9928): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
E/flutter ( 9928): #0 Navigator.of.<anonymous closure>
package:flutter/…/widgets/navigator.dart:2553
E/flutter ( 9928): #1 Navigator.of
package:flutter/…/widgets/navigator.dart:2560
E/flutter ( 9928): #2 _MyAppState.initState.<anonymous closure>
package:note_reminder/main.dart:42
E/flutter ( 9928): #3 _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 9928): #4 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 9928): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 9928): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter ( 9928): #7 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter ( 9928): #8 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter ( 9928): #9 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter ( 9928): #10 _rootRun (dart:async/zone.dart:1418:47)
E/flutter ( 9928): #11 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 9928): #12 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 9928): #13 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 9928): #14 _rootRun (dart:async/zone.dart:1426:13)
E/flutter ( 9928): #15 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 9928): #16 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 9928): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 9928): #18 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 9928): #19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter ( 9928):
I/OpenGLRenderer( 9928): Davey! duration=567777ms; Flags=1, FrameTimelineVsyncId=76328, IntendedVsync=19427849009190, Vsync=19427849009190, InputEventId=0, HandleInputStart=19427850193500, AnimationStart=19427850214100, PerformTraversalsStart=19427851010200, DrawStart=19427851815400, FrameDeadline=19427899009188, FrameInterval=19427850132400, FrameStartTime=16666666, SyncQueued=19427852843800, SyncStart=19427853556300, IssueDrawCommandsStart=19427855478900, SwapBuffers=19427864095600, FrameCompleted=19995626844200, DequeueBufferDuration=7109800, QueueBufferDuration=670800, GpuCompleted=19995626844200, SwapBuffersCompleted=19427873795500, DisplayPresentTime=25614609433559128,
Also note that I am trying to route to a screen that I am using with a custom navbar.
Code of routes:
home: OnBoardingPage(),
routes: {
'done': (context) => DonePage(),
'create': (context) => CreatePage(),
'history': (context) => HistoryPage(),
Code of my Home Page:
class _HomePageState extends State<HomePage> {
int _currentIndex = 0;
final screens = [DonePage(), CreatePage(), HistoryPage()];
#override
Widget build(BuildContext context) => SafeArea(
child: Scaffold(
body: screens[_currentIndex],
)

Related

Audio Service How to retrieve a variable with a StateFul widget

For my project I use the packages audioplayers for my audio sound and I need to use the sound in background and to control it with the notification and for that I use the package audio_service and now I have a problem.
First of all I want to precise I use this class to retrieve the song and others variables from an other page.
class MyPlayerController extends StatefulWidget {
final Song songToPlay;
final List<Song> playlist;
final Color backgroundColor;
const MyPlayerController({required this.songToPlay, required this.playlist, required this.backgroundColor});
#override
AudioPlayerHandler createState() => AudioPlayerHandler();
}
Now I declare all of this to control my audio player :
class AudioPlayerHandler extends BaseAudioHandler with State<MyPlayerController>,Diagnosticable{
late AudioHandler audioHandler;
late AudioPlayer audioPlayer;
late Song song;
AudioCache? audioCache;
double soundMax = 1;
double soundPosition = 0.5;
Duration position = const Duration(seconds: 0);
Duration maxDuration = const Duration(seconds: 0);
bool playShuffle = false;
bool repeat = false;
IconData iconData = Icons.play_circle;
#override
void initState() {
super.initState();
}
#override
void dispose() {
clearPlayer();
super.dispose();
}
#override
Future<void> play() async {
playbackState.add(playbackState.value.copyWith(
playing: true,
controls: [MediaControl.pause],
));
await setupPlayer();
}
#override
Future<void> pause() async {
playbackState.add(playbackState.value.copyWith(
playing: false,
controls: [MediaControl.play],
));
await audioPlayer.pause();
}
After that when i call the setupPlayer
setupPlayer() {
song = widget.songToPlay;
audioPlayer = AudioPlayer();
audioPlayer.onPlayerStateChanged.listen(onStateChange);
audioPlayer.onDurationChanged.listen(onDurationChange);
audioPlayer.onAudioPositionChanged.listen(onAudioPositionChanged);
final url = song.path;
audioPlayer.play(url);
//changeVolume(soundPosition);
}
That made me this error
E/flutter (10633): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter (10633): #0 State.widget (package:flutter/src/widgets/framework.dart:916:26)
E/flutter (10633): #1 AudioPlayerHandler.setupPlayer (package:easyislam/view/spotify/controllers/player_controller.dart:190:12)
E/flutter (10633): #2 AudioPlayerHandler.play (package:easyislam/view/spotify/controllers/player_controller.dart:233:11)
E/flutter (10633): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
E/flutter (10633): #4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
E/flutter (10633): #5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
E/flutter (10633): #6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter (10633): #7 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
E/flutter (10633): #8 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:563:9)
E/flutter (10633): #9 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
E/flutter (10633): #10 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
E/flutter (10633): #11 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
E/flutter (10633): #12 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
E/flutter (10633): #13 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
E/flutter (10633): #14 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter (10633): #15 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter (10633): #16 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
E/flutter (10633): #17 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter (10633): #18 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter (10633): #19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter (10633): #20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter (10633): #21 _rootRunUnary (dart:async/zone.dart:1442:13)
E/flutter (10633): #22 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (10633): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter (10633): #24 _invoke1 (dart:ui/hooks.dart:170:10)
E/flutter (10633): #25 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
E/flutter (10633): #26 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
I tried to retrieve the song with a setState :
setState(() {
song = widget.songToPlay;
});
audioPlayer = AudioPlayer();
audioPlayer.onPlayerStateChanged.listen(onStateChange);
audioPlayer.onDurationChanged.listen(onDurationChange);
audioPlayer.onAudioPositionChanged.listen(onAudioPositionChanged);
final url = song.path;
audioPlayer.play(url);
//changeVolume(soundPosition);
}
And that made me this error :
E/flutter (10633): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called in constructor: AudioPlayerHandler#ee85b
E/flutter (10633): This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.
E/flutter (10633): #0 State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1109:9)
E/flutter (10633): #1 State.setState (package:flutter/src/widgets/framework.dart:1120:6)
E/flutter (10633): #2 AudioPlayerHandler.setupPlayer (package:easyislam/view/spotify/controllers/player_controller.dart:190:5)
E/flutter (10633): #3 AudioPlayerHandler.play (package:easyislam/view/spotify/controllers/player_controller.dart:236:11)
E/flutter (10633): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
E/flutter (10633): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
E/flutter (10633): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
E/flutter (10633): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter (10633): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
E/flutter (10633): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:563:9)
E/flutter (10633): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
E/flutter (10633): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
E/flutter (10633): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
E/flutter (10633): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
E/flutter (10633): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
E/flutter (10633): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter (10633): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter (10633): #17 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
E/flutter (10633): #18 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter (10633): #19 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter (10633): #20 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter (10633): #21 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter (10633): #22 _rootRunUnary (dart:async/zone.dart:1442:13)
E/flutter (10633): #23 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (10633): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter (10633): #25 _invoke1 (dart:ui/hooks.dart:170:10)
E/flutter (10633): #26 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
E/flutter (10633): #27 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
I use this packages :
import 'package:audio_service/audio_service.dart';
import 'package:audioplayers/audioplayers.dart';
I want to know how I can retrieve this song without this error.

How to execute write method in function that changes value in slidebar?

When the slide bar value changes, it tries to write a packet.
I am using the example,
I made a function and tried it, but a null error occurs. (discoverService, characteristic.., etc.)
How can I solve this?
I'm using flutter_blue
In the flutter_blue example, write works fine.
I'm flutter beginer.
I need your help. thank you.
https://pub.dev/packages/flutter_blue
onWriteData
var data = [0x80, 0x80, 0xF0, 0x7D, 0x05, 0x00, 0x0E, 0x01, 60, 100, 00,0x80, 0xF7];
FlutterBlue flutterBlue = FlutterBlue.instance;
BluetoothDevice device;
BluetoothService service;
onWriteData() async {
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
});
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
List<int> value = await c.read();
print(value);
await c.write(data);
}
}
slideBar class
class slidecontrollerr extends State<slidecontroller> {
static double volumeValue = 60;
void onVolumeChanged(double value) async { **// I want to execute the write function here**
setState(() {
volumeValue = value;
});
onWriteData(); **//error**
}
#override
Widget build(BuildContext context) {
return Scaffold(
.
.
.
[Error Code][1]
E/flutter ( 5640): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'discoverServices' was called on null.
E/flutter ( 5640): Receiver: null
E/flutter ( 5640): Tried calling: discoverServices()
E/flutter ( 5640): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter ( 5640): #1 onWriteData (package:auto_humidity/main.dart:467:48)
E/flutter ( 5640): #2 slidecontrollerr.onVolumeChanged (package:auto_humidity/main.dart:1489:5)
E/flutter ( 5640): #3 RenderRadialAxisParent.createPointerValueChangedArgs (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:584:43)
E/flutter ( 5640): #4 RenderRadialAxisParent._setCurrentPointerValue (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:548:5)
E/flutter ( 5640): #5 RenderRadialAxisParent._updateDragValue (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:527:7)
E/flutter ( 5640): #6 RenderRadialAxisParent._updatePointerValue (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:452:7)
E/flutter ( 5640): #7 RenderRadialAxisParent._handleDragUpdate (package:syncfusion_flutter_gauges/src/radial_gauge/axis/radial_axis_parent_widget.dart:339:5)
E/flutter ( 5640): #8 DragGestureRecognizer._checkUpdate.<anonymous closure> (package:flutter/src/gestures/monodrag.dart:436:55)
E/flutter ( 5640): #9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter ( 5640): #10 DragGestureRecognizer._checkUpdate (package:flutter/src/gestures/monodrag.dart:436:7)
E/flutter ( 5640): #11 DragGestureRecognizer.handleEvent (package:flutter/src/gestures/monodrag.dart:289:9)
E/flutter ( 5640): #12 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:93:12)
E/flutter ( 5640): #13 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:138:9)
E/flutter ( 5640): #14 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter ( 5640): #15 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:136:18)
E/flutter ( 5640): #16 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:122:7)
E/flutter ( 5640): #17 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter ( 5640): #18 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter ( 5640): #19 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:287:11)
E/flutter ( 5640): #20 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter ( 5640): #21 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter ( 5640): #22 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter ( 5640): #23 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter ( 5640): #24 _rootRunUnary (dart:async/zone.dart:1370:13)
E/flutter ( 5640): #25 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 5640): #26 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter ( 5640): #27 _invoke1 (dart:ui/hooks.dart:182:10)
E/flutter ( 5640): #28 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter ( 5640): #29 _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)
You need to connect to a specific service and characteristics of your BLE device
Here is a piece of code that I am using
final String serviceUUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
final String characteristicWriteUUID = "0000fff1-0000-1000-8000-00805f9b34fb";
final String characteristicReadUUID = "0000fff2-0000-1000-8000-00805f9b34fb";
These services and characteristics must be set in the module itself by default or by you manually
discoverServices(BluetoothDevice device) async {
if (device == null) return;
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) {
// do something with service
if (service.uuid.toString().toLowerCase() == serviceUUID) {
service.characteristics.forEach((characteristic) {
if (characteristic.uuid.toString().toLowerCase() == characteristicReadUUID) {
targetReadCharacteristic = characteristic;
_readData(targetReadCharacteristic);
}
if (characteristic.uuid.toString().toLowerCase() == characteristicWriteUUID) {
targetWriteCharacteristic = characteristic;
writeData(targetWriteCharacteristic, [0x49, 0x44, 0x02]);
}
});
}
});
}
Future<void> writeData(characteristic, data) async{
if (characteristic == null) return;
try {
List<int> bytes = data;
await characteristic.write(bytes, withoutResponse: true );
print("data: Send: $data");
} catch (e) {
print('Data Error ${e.message} | $data');
}
}
_readData(characteristic) async {
if (!characteristic.isNotifying) {
await characteristic.setNotifyValue(true);
}
readSubScription = characteristic.value.listen((value) {
List<int> readData = new List.from(value);
if(readData.isNotEmpty && readData != []){
print('BLE read data: $readData');
}
});
}

NoSuchMethodError: The method '[]' was called on null. flutter local json file

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 8471): Receiver: null
E/flutter ( 8471): Tried calling: []("runnerId")
E/flutter ( 8471): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 8471): #1 new Metadata.fromMap (package:jsonfatch/model/event.dart:348:22)
E/flutter ( 8471): #2 new MarketRunner.fromMap (package:jsonfatch/model/event.dart:329:28)
E/flutter ( 8471): #3 new Market.fromMap.<anonymous closure> (package:jsonfatch/model/event.dart:138:52)
E/flutter ( 8471): #4 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
E/flutter ( 8471): #5 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
E/flutter ( 8471): #6 new List.from (dart:core-patch/array_patch.dart:57:19)
E/flutter ( 8471): #7 new Market.fromMap (package:jsonfatch/model/event.dart:137:18)
E/flutter ( 8471): #8 new EventDetails.fromMap.<anonymous closure> (package:jsonfatch/model/event.dart:65:62)
E/flutter ( 8471): #9 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
E/flutter ( 8471): #10 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
E/flutter ( 8471): #11 new List.from (dart:core-patch/array_patch.dart:57:19)
E/flutter ( 8471): #12 new EventDetails.fromMap (package:jsonfatch/model/event.dart:65:11)
E/flutter ( 8471): #13 HomePageState.loadData.<anonymous closure> (package:jsonfatch/home.dart:28:51)
E/flutter ( 8471): #14 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
E/flutter ( 8471): #15 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
E/flutter ( 8471): #16 new List.from (dart:core-patch/array_patch.dart:38:29)
E/flutter ( 8471): #17 new List.of (dart:core-patch/array_patch.dart:68:17)
E/flutter ( 8471): #18 ListIterable.toList (dart:_internal/iterable.dart:211:44)
E/flutter ( 8471): #19 HomePageState.loadData (package:jsonfatch/home.dart:29:10)
E/flutter ( 8471): <asynchronous suspension>
E/flutter ( 8471): #20 HomePageState.initState (package:jsonfatch/home.dart:19:5)
E/flutter ( 8471): #21 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4765:58)
E/flutter ( 8471): #22 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
E/flutter ( 8471): #23 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
E/flutter ( 8471): #24 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
E/flutter ( 8471): #25 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1252:16)
E/flutter ( 8471): #26 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1223:5)E/flutter ( 8471): #27 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1165:17)
E/flutter ( 8471): #28 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2683:19)
E/flutter ( 8471): #29 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1164:13)
E/flutter ( 8471): #30 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:974:7)
E/flutter ( 8471): #31 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:955:7)
E/flutter ( 8471): #32 _rootRun (dart:async/zone.dart:1182:47)
E/flutter ( 8471): #33 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 8471): #34 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 8471): #35 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 8471): #36 _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 8471): #37 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 8471): #38 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter ( 8471): #39 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 8471): #40 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter ( 8471): #41 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter ( 8471): #42 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
my json file in which the data is nested key value per and do many json obj
"runners":[
{
"id":10301,
"name":"roman",
"sortPriority":0,
"metadata":{
"runnerId":"10301"
}
},
{
"id":7337,
"name":"khali",
"sortPriority":0,
"metadata":{
"runnerId":"7337"
}
}
],
my map code for the runnerId. it was an nested array object. other all i have maped in model file
class Metadata {
Metadata({
this.runnerId,
});
String runnerId;
factory Metadata.fromMap(Map<String, dynamic> map) => Metadata(
runnerId: map["runnerId"],
);
Map<String, dynamic> toMap() => {
"runnerId": runnerId,
};
}
My Home.dart Code
class HomePage extends StatefulWidget {
#override
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
loadData();
}
loadData() async {
await Future.delayed(Duration(seconds: 2));
var cktJson = await rootBundle.loadString("assets/files/ckt.json");
var decodedData = jsonDecode(cktJson);
var cricketData = decodedData["cktdata"];
EventsModel.markets = List.from(cricketData)
.map<EventDetails>((item) => EventDetails.fromMap(item))
.toList();
setState(() {});
print("Decoded :-"+decodedData);
print("CrircktD :-"+ cricketData);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
backgroundColor: MainBackgroundColor,
title: Text("Radhe Json Fatch"),
),
body: SafeArea(
child: Column(
children: [
Expanded(
child: (EventsModel.markets != null && EventsModel.markets.isNotEmpty)?
ListView.builder(
scrollDirection: Axis.vertical,
itemCount: EventsModel.markets.length,
itemBuilder: (context, index) {
return LiveEventCricket(item: EventsModel.markets[index]);
},
):Center(child: CircularProgressIndicator()),
),
],
),
),
),
);
}
}

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

Flutter method channel error. { Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel battery) }

so i followed everthing from 'https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-java-tab' but when I click the floating button in my device this error is shown.
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel battery)
E/flutter ( 4580): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:159:7)
E/flutter ( 4580): <asynchronous suspension>
E/flutter ( 4580): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter ( 4580): #2 _batteryState._getBatteryLevel (package:flutter_app/main.dart:45:37)
E/flutter ( 4580): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter ( 4580): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter ( 4580): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 4580): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 4580): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 4580): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
E/flutter ( 4580): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
E/flutter ( 4580): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
E/flutter ( 4580): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
E/flutter ( 4580): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4580): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
E/flutter ( 4580): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
E/flutter ( 4580): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
E/flutter ( 4580): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 4580): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 4580): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 4580): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 4580): #20 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4580): #21 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4580): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4580): #23 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 4580): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter ( 4580):
Main.dart:-
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main(){
runApp(
MaterialApp(
home: battery()
)
);
}
class battery extends StatefulWidget {
#override
_batteryState createState() => _batteryState();
}
class _batteryState extends State<battery> {
static const platform = const MethodChannel('battery');
String _batteryLevel = 'error';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BatteryDetails'),
),
body: Center(
child: Column(
children: <Widget>[
FloatingActionButton.extended(onPressed: _getBatteryLevel, label: Text('Get battery info')),
Text(_batteryLevel),
],
)
)
);
}
Future<void> _getBatteryLevel() async{
String BatteryLevel;
try {
final int result = await platform.invokeMethod('getBatteryLevel');
BatteryLevel = 'battery Level is $result %.';
}on PlatformException catch (e){
BatteryLevel = "failed to get battery level: '&{e.message}'";
}
setState(() {
_batteryLevel = BatteryLevel;
});
}
}
MainActivity.java:-
package com.example.flutter_app;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "battery";
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
// Note: this method is invoked on the main thread.
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
);
}
private int getBatteryLevel() {
int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
return batteryLevel;
}
}
i am new to flutter, can you help me also can anyone explain me what is happening in
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result)
this part of code.
thank you.
Based from the the error you got, you're getting a MissingPluginException from the method getBatteryLevel. This means the app is unable to find the method you're trying to call.
If you just tried running the app using hot reload, changes on platform-specific code might have not registered. Running the app using restart should usually solve the issue. If you're still having issues, you can print the log of the call.method being passed to the MethodChannel in your MainActivity.java to see if the method name from Flutter is being received as expected.
When using native features, always add the required dependencies in either Info.plist or AndroidManifest.xml and always re-install the whole app, hot-restart/reload won't always work if you all of a sudden implement some new code that accesses native device features.