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');
}
});
}
Related
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.
[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()),
),
],
),
),
),
);
}
}
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
I want to upload the screenshot image to Firestore, but I am having some null errors,
Future uploadImagetoFirebase() async {
await screenshotController.capture().then((value) => (File image) {
_screenshot = image;
});
String fileName = _screenshot.path;
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('orders/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_screenshot);
TaskSnapshot taskSnapshot = await uploadTask;
taskSnapshot.ref.getDownloadURL().then((value) => print('Done: $value'));
}
I am calling it with button like this:
onPressed: () async {
await uploadImagetoFirebase(); }
This is the error stack:
flutter ( 5143): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The getter 'path' was called on null.
E/flutter ( 5143): Receiver: null
E/flutter ( 5143): Tried calling: path
E/flutter ( 5143): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 5143): #1 _CartState.uploadImagetoFirebase
package:CWCFlutter/model/cart.dart:88
E/flutter ( 5143): <asynchronous suspension>
E/flutter ( 5143): #2 _CartState.build.<anonymous closure>.<anonymous closure>.<anonymous closure>.<anonymous closure>
package:CWCFlutter/model/cart.dart:310
E/flutter ( 5143): #3 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:993
E/flutter ( 5143): #4 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1111
E/flutter ( 5143): #5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:183
E/flutter ( 5143): #6 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:598
E/flutter ( 5143): #7 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:287
E/flutter ( 5143): #8 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:222
E/flutter ( 5143): #9 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:476
E/flutter ( 5143): #10 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:77
E/flutter ( 5143): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:122
E/flutter ( 5143): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 5143): #13 PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:120
E/flutter ( 5143): #14 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:106
E/flutter ( 5143): #15 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:358
E/flutter ( 5143): #16 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:338
E/flutter ( 5143): #17 RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:267
E/flutter ( 5143): #18 GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:295
E/flutter ( 5143): #19 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:240
E/flutter ( 5143): #20 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:213
E/flutter ( 5143): #21 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 5143): #22 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 5143): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 5143): #24 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter ( 5143): #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
I am not sure how path was called on null, any ideas? Basically I await for the app to take a screenshot, then add that image in _screenshot File variable, then try to store it in 'orders' folder in Firestore. I have searched for answers, and they say you need to initialize Firestore somewhere, but I am not sure where that would be, I have only worked with older versions, and not sure how to do all things in the newer ones. Thank you!
I have tried setting the state as well, but getting the same error:
Future uploadImagetoFirebase() async {
await screenshotController.capture().then((value) => (File image) {
setState(() {
_screenshot = image;
});
});
What I came up with that seems to work as a solution
Future<String> uploadImagetoFirebase2() async {
File img = await screenshotController.capture();
setState(() {
_screenshot = img;
});
//change filename not to be path, but something else short
String fileName = img.path;
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('orders/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_screenshot);
TaskSnapshot taskSnapshot = (await uploadTask);
String uri = await taskSnapshot.ref.getDownloadURL();
print(uri);
return uri;
}
flutter ( 5143): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The getter 'path' was called on null.
E/flutter ( 5143): Receiver: null
E/flutter ( 5143): Tried calling: path
your path is null,
you can solve this in two ways
1. setstate
Future uploadImagetoFirebase() async {
await screenshotController.capture().then((value) => (File image) {
setState(() {
_screenshot = image;
});
});
//... your fireabase upload function
2 return from future
Future <File> uploadImagetoFirebase() async {
File myImage=await screenshotController.capture();
retun myImage
);
//get image onPress btn
onPressed: () async {
var myFile= await uploadImagetoFirebase();
//check if path is null using if ...
print(myFile.path);
// firebase function
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('orders/${myFile.path}');
UploadTask uploadTask = firebaseStorageRef.putFile(myFile);
TaskSnapshot taskSnapshot = (await uploadTask);
String uri = await taskSnapshot.ref.getDownloadURL();
print(uri);
return uri;
}
try this;
Future<String> uploadImagetoFirebase() async {
File img = await screenshotController.capture();
String fileName = img.path;
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('orders/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_screenshot);
TaskSnapshot taskSnapshot = (await uploadTask);
String uri = await taskSnapshot.ref.getDownloadURL();
print(uri);
return uri;
}
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.