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;
}
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.
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');
}
});
}
I'm studying flutter with Sqflite and trying to make a small app, but I'm getting this error when I run the code, I've looked literaly everywhere to findout what it could be.
Here the code code who use the Sqflite package:
Future<Database> getDatabase() async {
final String path = join(await getDatabasesPath(), 'bytebank.db');
return openDatabase(path, onCreate: (db, version) {
db.execute('CREATE TABLE contacts'
'(id INTEGER PRIMARY KEY, '
'name TEXT, '
'account_number INTEGER)');
}, version: 1);
}
Future<int> save(Contact contact) async {
final Database db = await getDatabase();
final Map<String, dynamic> contactMap = Map();
contactMap['name'] = contact.name;
contactMap['account_number'] = contact.account;
contactMap['id'] = contact.id;
return db.insert('contacts', contactMap);
}
Future<List<Contact>> findAll() async {
final Database db = await getDatabase();
final List<Map<String, dynamic>> result = await db.query('contacts');
final List<Contact> contacts = [];
for (Map<String, dynamic> row in result) {
final Contact contact = Contact(
row['id'],
row['name'],
row['account_number'],
);
contacts.add(contact);
}
return contacts;
}
And here is the only one place where I use This functions:
void main() {
save(Contact('William', 2, 13456)).then((id) {
findAll().then((contacts) => print(contacts));
});
runApp(ByteBankApp());
}
Model Class:
class Contact {
final String name;
final int account;
final int id;
Contact( this.id,
this.name,
this.account,
);
#override
String toString() {
return 'Contact{name: $name, account: $account}';
}
}
Error Trace back:
Launching lib\main.dart on sdk gphone x86 arm in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:52296/07rtnvW9tlQ=/ws
Syncing files to device sdk gphone x86 arm...
E/flutter (28649): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (28649): #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
E/flutter (28649): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
E/flutter (28649): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
E/flutter (28649): #3 invokeMethod (package:sqflite/src/sqflite_impl.dart:17:13)
E/flutter (28649): #4 SqfliteDatabaseFactoryImpl.invokeMethod (package:sqflite/src/factory_impl.dart:82:7)
E/flutter (28649): #5 SqfliteDatabaseFactoryMixin.safeInvokeMethod.<anonymous closure> (package:sqflite_common/src/factory_mixin.dart:41:38)
E/flutter (28649): #6 wrapDatabaseException (package:sqflite/src/exception_impl.dart:7:32)
E/flutter (28649): #7 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:78:7)
E/flutter (28649): #8 SqfliteDatabaseFactoryMixin.safeInvokeMethod (package:sqflite_common/src/factory_mixin.dart:41:7)
E/flutter (28649): #9 SqfliteDatabaseFactoryMixin.getDatabasesPath (package:sqflite_common/src/factory_mixin.dart:153:26)
E/flutter (28649): #10 getDatabasesPath (package:sqflite/sqflite.dart:161:54)
E/flutter (28649): #11 getDatabase (package:bytebank/database/app_database.dart:6:34)
E/flutter (28649): #12 save (package:bytebank/database/app_database.dart:16:29)
E/flutter (28649): #13 main (package:bytebank/main.dart:7:3)
E/flutter (28649): #14 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (28649): #15 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (28649): #16 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (28649): #17 _runZoned (dart:async/zone.dart:1789:10)
E/flutter (28649): #18 runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (28649): #19 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (28649): #20 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (28649): #21 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (28649):
I am not sure if will help, but I was running into a similar issue when initializing a database in an async "main" method. Adding the following:
WidgetsFlutterBinding.ensureInitialized();
inside the method before the code initializing the database solved the problem.
I am trying to upload multiple images to server but always get issues. I tried some other solutions as well but not working.
saveImages() async {
// string to uri
Uri uri = Uri.parse('http://100.0.50.10:8000/API/AddImageCarSale/Post');
// create multipart request
MultipartRequest request = http.MultipartRequest("POST", uri);
if (images != null) {
for (var i = 0; i < images.length; i++) {
ByteData byteData = await images[i].getByteData();
List<int> imageData = byteData.buffer.asUint8List();
MultipartFile multipartFile = MultipartFile.fromBytes(
'photo', //key of the api
imageData,
filename: images[i].name,
contentType: MediaType("image",
"jpg"), //this is not nessessory variable. if this getting error, erase the line.
);
request.fields['PhoneNo'] = '1122';
request.fields['VehicleNo'] = '1234';
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
}
}
}
My error is
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Bad state: Can't finalize a finalized Request.
E/flutter (11521): #0 BaseRequest.finalize (package:http/src/base_request.dart:104:20)
E/flutter (11521): #1 MultipartRequest.finalize (package:http/src/multipart_request.dart:92:11)
E/flutter (11521): #2 IOClient.send (package:http/src/io_client.dart:28:26)
E/flutter (11521): #3 BaseRequest.send (package:http/src/base_request.dart:119:35)
E/flutter (11521): #4 _SellerFormState.savedNew (package:Autolog/pages/buySell/sellerForm.dart:361:38)
E/flutter (11521):
E/flutter (11521): #5 _SellerFormState._buildBody. (package:Autolog/pages/buySell/sellerForm.dart:754:25)
E/flutter (11521): #6 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter (11521): #7 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter (11521): #8 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter (11521): #9 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter (11521): #10 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter (11521): #11 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:256:7)
E/flutter (11521): #12 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:158:27)
E/flutter (11521): #13 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:224:20)
E/flutter (11521): #14 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter (11521): #15 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter (11521): #16 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter (11521): #17 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter (11521): #18 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (11521): #19 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (11521): #20 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (11521): #21 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter (11521): #22 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter (11521):
You need to create a new multipart request for every loop as multipart request gets finalized.
Try this modification and it should work.
// string to uri
Uri uri = Uri.parse('http://100.0.50.10:8000/API/AddImageCarSale/Post');
// create multipart request
if (images != null) {
for (var i = 0; i < images.length; i++) {
MultipartRequest request = http.MultipartRequest("POST", uri);
ByteData byteData = await images[i].getByteData();
List<int> imageData = byteData.buffer.asUint8List();
MultipartFile multipartFile = MultipartFile.fromBytes(
'photo', //key of the api
imageData,
filename: images[i].name,
contentType: MediaType("image",
"jpg"), //this is not nessessory variable. if this getting error, erase the line.
);
request.fields['PhoneNo'] = '1122';
request.fields['VehicleNo'] = '1234';
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
}
}
}
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