error of no such metheod and jsonDocumentReference - flutter

I have a project where I want to update the status of a user to the firebase database and also update the status on Get storage I have written a code that gives me two errors
1. this error Happens when I upload the document to the firebase database it works fine and i can see the changes in database but somehow giving these exception it says :
E/flutter ( 2958): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_JsonDocumentReference'
E/flutter ( 2958): #0 _JsonStringifier.writeObject (dart:convert/json.dart:794:7)
E/flutter ( 2958): #1 _JsonStringifier.writeMap (dart:convert/json.dart:875:7)
E/flutter ( 2958): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:830:21)
E/flutter ( 2958): #3 _JsonStringifier.writeObject (dart:convert/json.dart:785:9)
E/flutter ( 2958): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:983:17)
E/flutter ( 2958): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:968:5)
E/flutter ( 2958): #6 JsonEncoder.convert (dart:convert/json.dart:345:30)
E/flutter ( 2958): #7 JsonCodec.encode (dart:convert/json.dart:231:45)
E/flutter ( 2958): #8 StorageImpl.flush (package:get_storage/src/storage/io.dart:34:37)
E/flutter ( 2958): #9 GetStorage._flush (package:get_storage/src/storage_impl.dart:144:23)
E/flutter ( 2958): #10 GetQueue._check (package:get/get_utils/src/queue/get_queue.dart:42:47)
E/flutter ( 2958): #11 GetQueue.add (package:get/get_utils/src/queue/get_queue.dart:29:5)
E/flutter ( 2958): #12 GetStorage._addToQueue (package:get_storage/src/storage_impl.dart:139:18)
E/flutter ( 2958): #13 Microtask.exec.<anonymous closure> (package:get_storage/src/storage_impl.dart:174:17)
E/flutter ( 2958): #14 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 2958): #15 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter ( 2958):
W/le.helping_han( 2958): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed)
[GETX] GOING TO ROUTE /Profile
here is my secondd error :
2. the second one I cannot understand the error, after i upload the document to firebase and i go to profile i get this error : after I hot-reload the error is gone
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Profile(dirty):
Class '_JsonDocumentReference' has no instance method '[]'.
Receiver: Instance of '_JsonDocumentReference'
Tried calling: []("status")
The relevant error-causing widget was:
Profile Profile:file:///D:/FIVERR%20PROJECTS%20FLUTTER/helping_hand/helping_hand/lib/drawers/Slidedrawer.dart:22:20
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1 Profile.build (package:helping_hand/UI/Other/Profile.dart:65:120)
#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4949:49)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#5 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
#6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
... Normal element mounting (275 frames)
here is my code :
BarController.dart (using GetxController)
// status
Future<void> addStatus(Map<String,String> userStatus) async {
loadingbar();
try{
final DocumentReference userstatus= FirebaseFirestore.instance
.collection('users')
.doc(Auth().currentuser?.email);
await userstatus.update({
"status":userStatus['status'],"description":userStatus['description'],
});
Userbox.write('userStatus', userstatus);
}catch(e){
if (kDebugMode) {
print('add status error ::: $e');
}
Get.snackbar('error','we have encountered an error');
}
loadingbaroff();
}
bool isloading = false;
void loadingbar() {
isloading = true;
update();
}
void loadingbaroff() {
isloading = false;
update();
}
Mystatus.dart :
Container(
width: MediaQuery.of(context).size.width-50,
margin: const EdgeInsets.only(top: 16,bottom: 24,left: 8,right: 8),
child: ElevatedButton(
style: const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent) ),
onPressed: () async {
if(selectpartycontroller.text.isNotEmpty&&description.text.isNotEmpty){
Map<String,String> userstatus = ({"status":selectpartycontroller.text.toString(), "description":description.text.toString(),});
await barController.addStatus(userstatus);
selectpartycontroller.clear();
description.clear();
if (kDebugMode) {
print(Userbox.read(Userbox.read('userdata')['country_code']));
}
}else{
Get.snackbar('fill details', 'select an option and add a description');
}
},
child:const Text('Continue',style: TextStyle(color: Colors.white),))),
profile.dart :
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.only(top: 24,bottom: 12,left: 24,right: 12),
child: Text('User status : ${Userbox.read('userStatus') == null? 'not fetched':Userbox.read('userStatus')['status']}',
style: const TextStyle(color: Colors.redAccent,fontWeight: FontWeight.normal,fontSize: 16),),),
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.only(top: 24,bottom: 12,left: 24,right: 12),
child: Text('status description : ${Userbox.read('userStatus')== null?'not fetched':Userbox.read('userStatus')['description']}',
style: const TextStyle(color: Colors.redAccent,fontWeight: FontWeight.normal,fontSize: 16),),),

for the first error, check the directory with the issue and see how you can fix that.
Profile Profile:file:///D:/FIVERR%20PROJECTS%20FLUTTER/helping_hand/helping_hand/lib/drawers/Slidedrawer.dart:22:20
The reason you're getting the second error is that the key "status" was null so to handle that, add a null check,
// status
Future<void> addStatus(Map<String, String> userStatus) async {
loadingbar();
try {
final DocumentReference userstatus = FirebaseFirestore.instance
.collection('users')
.doc(Auth().currentuser?.email);
await userstatus.update({
if (userStatus['status'] != null) "status": userStatus['status'],
if (userStatus['description'] != null)
"description": userStatus['description'],
});
Userbox.write('userStatus', userstatus);
} catch (e) {
if (kDebugMode) {
print('add status error ::: $e');
}
Get.snackbar('error', 'we have encountered an error');
}
loadingbaroff();
}
bool isloading = false;
void loadingbar() {
isloading = true;
update();
}
void loadingbaroff() {
isloading = false;
update();
}
On the userstatus, you'll want to remove the "toString()" method and clear Controllers after the entire Operations
Container(
width: MediaQuery.of(context).size.width-50,
margin: const EdgeInsets.only(top: 16,bottom: 24,left: 8,right: 8),
child: ElevatedButton(
style: const ButtonStyle(backgroundColor:MaterialStatePropertyAll(Colors.redAccent) ),
onPressed: () async {
if(selectpartycontroller.text.isNotEmpty&&description.text.isNotEmpty){
Map<String,String> userstatus = ({"status":selectpartycontroller, "description":description.text,});
await barController.addStatus(userstatus);
if (kDebugMode) {
print(Userbox.read(Userbox.read('userdata')['country_code']));
}
}else{
Get.snackbar('fill details', 'select an option and add a description');
}
selectpartycontroller.clear();
description.clear();},
child:const Text('Continue',style: TextStyle(color: Colors.white),))),

Related

Dart Stream Not Cancelling

I have a class that contains a stream that listens for objects to be created.
class Conversation {
// variables for live query
late QueryBuilder<ParseObject> message_live_query_;
final LiveQuery live_query = LiveQuery(debug: true);
// variables for streams
final message_added_stream_controller = StreamController<ParseObject>();
// constructor that gets messages and starts livequery
Conversation(this.conversation_, this.receiving_user_) {
// init and active live query
message_live_query_ = QueryBuilder<ParseObject>(ParseObject('Message'));
message_live_query_.whereEqualTo('conversation', conversation_);
initLiveQuery();
}
// returns the stream controller to be listened to
Stream get messageAddedStream => message_added_stream_controller.stream;
// listens to live query and if a message is detected, the stream notifies the listeners
void initLiveQuery() async {
final subscription = await live_query.client.subscribe(message_live_query_);
subscription.on(LiveQueryEvent.create, (message) {
print('*** MESSAGE CREATED FOR CONVERSATION OBJECT $getObjectID');
print('$message');
// notify the stream and add to local list
if(message_added_stream_controller.hasListener) { /// check if there is a listener, if not, don't add the value
message_added_stream_controller.add(message);
}
latest_message_ = message;
messages.add(message);
});
}
}
In a view I start listening to the stream with a stream listener, and when the user hits the back button I call another function to cancel the stream listener.
class _DirectMessageState extends State<DirectMessage> {
// list that holds messages
late List<types.Message> chatapp_message_list;
// variables for listening for new messages
StreamSubscription<dynamic>? messageAddedStreamListener = null;
// starts listening to stream
void listenMessageCreationStream() async {
// calls the classes getter function and starts listening to the stream
messageAddedStreamListener = widget.local_conversation.messageAddedStream.listen((message) {
print("MESSAGE HAS BEEN CREATED");
print(message);
if (message['sending_user_info']['objectId'] != widget.local_user.getUserInfoObjectID) {
setState(() {
chatapp_message_list.insert(0,convertToChatAppMessageObj(
message, chatapp_sending_user, chatapp_receiving_user));
});
}
});
}
#override
void initState() {
super.initState();
listenMessageCreationStream();
}
// cancels the listener and sets it to null
Future<void> disposeListeners() async {
await messageAddedStreamListener?.cancel();
messageAddedStreamListener = null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: BODY_BACKGROUND_COLOR,
appBar: AppBar(
backgroundColor: HEADER_FOOTER_BACKGROUND_COLOR,
title: const Text(
"Direct Message",
style: TextStyle(
color: TEXT_COLOR,
fontSize: SECONDARY_PAGE_HEADER_SIZE,
),
),
centerTitle: true,
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () async {
await disposeListeners(); // WAIT TO CANCEL SUBSCRIPTION HERE
globals.GlobalVars().navigatorKey.currentState?.pop(newlyCreatedListing);
}),
),
body: ...,
);
}
}
However when I navigate to the prior page, and re-navigate back to the DirectMessage page I get the following error that the stream is already being listened to
E/flutter ( 9347): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: Stream has already been listened to.
E/flutter ( 9347): #0 _StreamController._subscribe (dart:async/stream_controller.dart:676:7)
E/flutter ( 9347): #1 _ControllerStream._createSubscription (dart:async/stream_controller.dart:827:19)
E/flutter ( 9347): #2 _StreamImpl.listen (dart:async/stream_impl.dart:471:9)
E/flutter ( 9347): #3 _DirectMessageState.listenMessageCreationStream (package:supply_my_degree/social/direct_message.dart:88:79)
E/flutter ( 9347): #4 _DirectMessageState.initState (package:supply_my_degree/social/direct_message.dart:107:5)
E/flutter ( 9347): #5 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5015:57)
E/flutter ( 9347): #6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
E/flutter ( 9347): #7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
E/flutter ( 9347): #8 Element.updateChild (package:flutter/src/widgets/framework.dart:3592:18)
E/flutter ( 9347): #9 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6300:14)
E/flutter ( 9347): #10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
E/flutter ( 9347): #11 Element.updateChild (package:flutter/src/widgets/framework.dart:3592:18)
E/flutter ( 9347): #12 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4904:16)
E/flutter ( 9347): #13 Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
E/flutter ( 9347): #14 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
E/flutter ( 9347): #15 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
I'm not understanding how the stream isn't being cancelled by calling the disposeListeners() function before I exit the screen.

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

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

UnHandled Exception : Unable to capture the error

I am trying to use Firebase Auth with Flutter. Below is my code.
login_screen.dart
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5)),
color: blackShadeColor,
child: Text("Login",
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 16))),
onPressed: () {
_loginScreenController
.login(
context: context,
email: _emailController.text,
password: _passwordController.text)
.catchError((error) {
print(error);
});
},
),
login_screen_controller.dart
class LoginScreenController {
/**
* Login Function
*/
Future<void> login({BuildContext context, String email, String password}) async {
FirebaseAuthService firebaseAuthService = FirebaseAuthService();
firebaseAuthService.signInWithEmail(email, password).then(((value){})).catchError((onError){
throw onError;
});
}
}
firebase_auth_service.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class FirebaseAuthService with ChangeNotifier {
//Sign in with username and password
Future<void> signInWithEmail(String email, String password) async {
FirebaseAuth auth = FirebaseAuth.instance;
try {
UserCredential userCredential = await auth.signInWithEmailAndPassword(
email: email, password: password);
User user = userCredential.user;
if (user != null) {
print("Sign in success: " + user.email);
} else {
print("sign in failed");
throw Exception(
"Sign in Failed. Please check your email and password again");
}
} catch (e) {
print(e.toString());
throw (e);
} finally {
//notifyListeners();
}
}
}
If there is an error, like wrong password, wrong email or something, the firebase throws an error. The issue is my attempts to catch that error is not working as expected. Instead I end up with Unhandled exception. This is the error I get.
I/flutter (18418): [firebase_auth/invalid-email] The email address is badly formatted.
E/flutter (18418): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: [firebase_auth/invalid-email] The email address is badly formatted.
[38;5;248mE/flutter (18418): #0 FirebaseAuthService.signInWithEmail[39;49m
package:wnenterprises/services/firebase_auth_service.dart
E/flutter (18418): <asynchronous suspension>
[38;5;248mE/flutter (18418): #1 LoginScreenController.login[39;49m
package:wnenterprises/controllers/login_screen_controller.dart
[38;5;248mE/flutter (18418): #2 _LoadingScreenState.build.<anonymous closure>[39;49m
package:wnenterprises/screens/login_screen.dart
[38;5;244mE/flutter (18418): #3 _InkResponseState._handleTap[39;49m
package:flutter/…/material/ink_well.dart
[38;5;244mE/flutter (18418): #4 _InkResponseState.build.<anonymous closure>[39;49m
package:flutter/…/material/ink_well.dart
[38;5;244mE/flutter (18418): #5 GestureRecognizer.invokeCallback[39;49m
package:flutter/…/gestures/recognizer.dart
[38;5;244mE/flutter (18418): #6 TapGestureRecognizer.handleTapUp[39;49m
package:flutter/…/gestures/tap.dart
[38;5;244mE/flutter (18418): #7 BaseTapGestureRecognizer._checkUp[39;49m
package:flutter/…/gestures/tap.dart
[38;5;244mE/flutter (18418): #8 BaseTapGestureRecognizer.acceptGesture[39;49m
package:flutter/…/gestures/tap.dart
[38;5;244mE/flutter (18418): #9 GestureArenaManager.sweep[39;49m
package:flutter/…/gestures/arena.dart
[38;5;244mE/flutter (18418): #10 GestureBinding.handleEvent[39;49m
package:flutter/…/gestures/binding.dart
[38;5;244mE/flutter (18418): #11 GestureBinding.dispatchEvent[39;49m
package:flutter/…/gestures/binding.dart
[38;5;244mE/flutter (18418): #12 RendererBinding.dispatchEvent[39;49m
package:flutter/…/rendering/binding.dart
[38;5;244mE/flutter (18418): #13 GestureBinding._handlePointerEvent[39;49m
package:flutter/…/gestures/binding.dart
[38;5;244mE/flutter (18418): #14 GestureBinding._flushPointerEventQueue[39;49m
package:flutter/…/gestures/binding.dart
[38;5;244mE/flutter (18418): #15 GestureBinding._handlePointerDataPacket[39;49m
package:flutter/…/gestures/binding.dart
[38;5;244mE/flutter (18418): #16 _rootRunUnary (dart:async/zone.dart:1206:13)[39;49m
[38;5;244mE/flutter (18418): #17 _CustomZone.runUnary (dart:async/zone.dart:1100:19)[39;49m
[38;5;244mE/flutter (18418): #18 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)[39;49m
[38;5;244mE/flutter (18418): #19 _invoke1 (dart:ui/hooks.dart:265:10)[39;49m
[38;5;244mE/flutter (18418): #20 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)[39;49m
E/flutter (18418):
What is really happening here?
Instead of async await, you can try the regular .then() method and use the catch error function. :
auth.signInWithEmailAndPassword(email: email, password: password).then((val){print(val);}).catchError((e){print("Exception: " + e.toString())});

I am getting error like this Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe

What I trying to do here is getting data from the 000webhost.com and passing that to my model class. That model class is being passed to the provider. Now when I try to display the information in my screen i am getting error.
In this case i have a model class called StudentData.
class StudentData {
final String rollNumber;
final String firstName;
final String lastName;
StudentData({
this.rollNumber,
this.firstName,
this.lastName,
});
}
Here I am fetching data using http package from internet.
And passing the decoded data to the StudentData class and passing that to my data_provider
import 'package:http/http.dart' as http;
void getStudentData(String currentEmail, BuildContext context) async {
final _url = 'https://aaa.000webhostapp.com/getStudentData.php';
final response = await http.post(_url, body: {'email': currentEmail});
var data = response.body;
final decodedData = jsonDecode(data);
final myRollNumber = decodedData['roll_number'];
final myFirstName = decodedData['first_name'];
final myLastName = decodedData['last_name'];
final myStudentData = StudentData(
rollNumber: myRollNumber, firstName: myFirstName, lastName: myLastName);
Provider.of<DataProvider>(context, listen: false)
.getMyStudentData(myStudentData);
}
Here is my DataProvider
class DataProvider extends ChangeNotifier {
StudentData myStudentData;
void getMyStudentData(StudentData studentData) {
myStudentData = studentData;
notifyListeners();
}
}
After that I have tried to fetch those information in my Screen
class StudentDashboard extends StatelessWidget {
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Center(
child:
Text(Provider.of<DataProvider>(context).myStudentData.rollNumber),
),
),
);
}
}
Then the error be like
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building StudentDashboard(dirty, dependencies: [_InheritedProviderScope<DataProvider>]):
The getter 'rollNumber' was called on null.
Receiver: null
Tried calling: rollNumber
The relevant error-causing widget was:
StudentDashboard file:///D:/Other/App/Flutter/my_ecampus/lib/views/screens/auth_screens/login_screen.dart:62:53
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 StudentDashboard.build (package:my_ecampus/views/screens/main_screens/student_screens/student_dashboard.dart:38:69)
#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4701:28)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
...
====================================================================================================
E/flutter ( 7682): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter ( 7682): At this point the state of the widget's element tree is no longer stable.
E/flutter ( 7682): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
E/flutter ( 7682): #0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3906:9)
E/flutter ( 7682): #1 Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3920:6)
E/flutter ( 7682): #2 Element.getElementForInheritedWidgetOfExactType (package:flutter/src/widgets/framework.dart:3986:12)
E/flutter ( 7682): #3 Provider._inheritedElementOf (package:provider/src/provider.dart:324:34)
E/flutter ( 7682): #4 Provider.of (package:provider/src/provider.dart:281:30)
E/flutter ( 7682): #5 getStudentData (package:my_ecampus/business_view/services/database/getData_database.dart:19:12)
E/flutter ( 7682): <asynchronous suspension>
E/flutter ( 7682): #6 LoginScreen._login (package:my_ecampus/views/screens/auth_screens/login_screen.dart:60:9)
E/flutter ( 7682): <asynchronous suspension>
E/flutter ( 7682): #7 LoginScreen.build.<anonymous closure>.<anonymous closure> (package:my_ecampus/views/screens/auth_screens/login_screen.dart:198:31)
E/flutter ( 7682): #8 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
E/flutter ( 7682): #9 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
E/flutter ( 7682): #10 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
E/flutter ( 7682): #11 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
E/flutter ( 7682): #12 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
E/flutter ( 7682): #13 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:259:7)
E/flutter ( 7682): #14 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
E/flutter ( 7682): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:362:20)
E/flutter ( 7682): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
E/flutter ( 7682): #17 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
E/flutter ( 7682): #18 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
E/flutter ( 7682): #19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
E/flutter ( 7682): #20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
E/flutter ( 7682): #21 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 7682): #22 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 7682): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 7682): #24 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter ( 7682): #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
E/flutter ( 7682):
This is my main class and i am using multiprovider here.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<WidgetProvider>(
create: (context) => WidgetProvider()),
ChangeNotifierProvider<DataProvider>(
create: (context) => DataProvider()),
],
child: MaterialApp(
home: LoginScreen(),
),
);
}
}
This is where I call getStudentData function
void _login({String email, String password, BuildContext context}) async {
final loginResponse =
await loginDatabase(email: email, password: password, context: context);
if (loginResponse.isNotEmpty) {
final isStaff = email.contains(RegExp(r'.ce#srit.org$'));
if (isStaff == true) {
getStaffData(email, context);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => StaffDashboard()));
} else {
getStudentData(email, context);//here is the getStudentData() function
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => StudentDashboard()));
}
} else {
print('Login Failed from loginDatabase(){}');
}
}
The HTTP request is sent to the provider listen: false because it can not listen. So that you can call the method. That's why I designed it from scratch for you. I hope you understand. It will probably work if you do it as I did.
import 'package:http/http.dart' as http;
Future<StudentData> _getStudentData(String currentEmail, BuildContext context)async {
final _url = 'https://aaa.000webhostapp.com/getStudentData.php';
final response = await http.post(_url, body: {'email': currentEmail});
var data = response.body;
if (data.isEmpty) return null;
final decodedData = jsonDecode(data);
final myRollNumber = decodedData['roll_number'];
final myFirstName = decodedData['first_name'];
final myLastName = decodedData['last_name'];
final myStudentData = StudentData(
rollNumber: myRollNumber, firstName: myFirstName, lastName: myLastName);
return MystudentData;
}
class DataProvider extends ChangeNotifier {
StudentData myStudentData;
void getMyStudentData(StudentData studentData) {
myStudentData = studentData;
notifyListeners();
}
}
Future getMyStudentDataAsync() async {
StudentData result = await _getStudentData();
getMyStudentData(result);
}
class StudentDashboard extends StatelessWidget {
#override
void initState() {
super.initState(); getRequest();
}
future getRequest()async{
Provider.of<DataProvider>(context, listen: false)
.getMyStudentDataAsync();
}
#override
Widget build(BuildContext context) {
DataProvider _dataProvider = Provider.of<DataProvider>(context);
return SafeArea(
child: Scaffold(
body: Center(
child:
Text( _dataProvider.myStudentData.rollNumber),
),
),
);
}
}

Problem with BLE module : Exception: Another scan is already in progress

I'm trying to make possible the following actions:
I run my app and when I press the "Connect" button I connect to my BLE module.
A second button allows me to disconnect from it.
The problem is that if I connect to the BLE module, and then press the disconnect button, it disconnect but I will no longer be able to connect to the BLE anymore (and I have to restart the app).
There is my code:
import 'dart:async';
import 'dart:convert' show utf8;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue/flutter_blue.dart';
void main() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft
]);
runApp(MainScreen());
}
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BLUETOOTH',
debugShowCheckedModeBanner: false,
home: Home(),
theme: ThemeData.dark(),
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String connectionText = "";
final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
final String TARGET_DEVICE_NAME = "MLT-BT05";
FlutterBlue flutterBlue = FlutterBlue.instance; // * Instance de FlutterBlue
StreamSubscription<ScanResult> scanSubScription; // * StreamSubscription
BluetoothDevice targetDevice; // * Device
BluetoothCharacteristic targetCharacteristic; // * Characteristiques
#override
void initState() {
super.initState();
// startScan();
}
startScan() {
setState(() {
connectionText = "Start Scanning";
});
scanSubScription = flutterBlue.scan().listen((scanResult) {
print(scanResult.device.name.toString()); // ! TEST
if (scanResult.device.name == TARGET_DEVICE_NAME) {
print('DEVICE found');
stopScan();
setState(() {
connectionText = "Found Target Device";
});
targetDevice = scanResult.device;
connectToDevice();
}
}, onDone: () => stopScan());
}
stopScan() {
scanSubScription?.cancel();
scanSubScription = null;
}
connectToDevice() async {
if (targetDevice == null) return;
setState(() {
connectionText = "Device Connecting";
});
await targetDevice.connect();
print('DEVICE CONNECTED');
setState(() {
connectionText = "Device Connected";
});
discoverServices();
}
disconnectFromDevice() {
if (targetDevice == null) return;
targetDevice.disconnect();
setState(() {
connectionText = "Device Disconnected";
});
}
discoverServices() async {
if (targetDevice == null) return;
List<BluetoothService> services = await targetDevice.discoverServices();
services.forEach((service) {
// do something with service
if (service.uuid.toString() == SERVICE_UUID) {
service.characteristics.forEach((characteristic) {
if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
targetCharacteristic = characteristic;
writeData("Hi there, ESP32!!");
setState(() {
connectionText = "All Ready with ${targetDevice.name}";
});
}
});
}
});
}
writeData(String data) {
if (targetCharacteristic == null) return;
List<int> bytes = utf8.encode(data);
targetCharacteristic.write(bytes);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(connectionText),
centerTitle: true,
),
body: Center(
child: Column(
children: <Widget>[
FlatButton(
child: Text("Connect"),
color: Colors.grey[700],
onPressed: () {
startScan();
},
),
FlatButton(
child: Text("Disconnect"),
color: Colors.grey[700],
onPressed: () {
disconnectFromDevice();
},
),
],
),
),
);
}
}
The error tells me that another scan is already in progress even though the scanSubScription is canceled and set to null once the device is connected.
The error:
I/flutter (13433): [TV] Samsung 7 Series (55)
I/flutter (13433): MLT-BT05
I/flutter (13433): DEVICE found
I/flutter (13433): DEVICE CONNECTED
E/flutter (13433): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Exception: Another scan is already in progress.
E/flutter (13433): #0 FlutterBlue.scan (package:flutter_blue/src/flutter_blue.dart:81:7)
E/flutter (13433): <asynchronous suspension>
E/flutter (13433): #1 _HomeState.startScan (package:bluetoothv8/main.dart:53:36)
E/flutter (13433): #2 _HomeState.build.<anonymous closure> (package:bluetoothv8/main.dart:140:17)
E/flutter (13433): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (13433): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (13433): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (13433): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (13433): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (13433): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (13433): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (13433): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (13433): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (13433): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (13433): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (13433): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (13433): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (13433): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (13433): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (13433): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (13433): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (13433): #20 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (13433): #21 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (13433): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (13433): #23 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (13433): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
Instead of:
stopScan() {
scanSubScription?.cancel();
scanSubScription = null;
}
write:
stopScan() {
flutterBlue.stopScan();
scanSubScription?.cancel();
scanSubScription = null;
}
please use like this
bluetoothInstance.stopScan().then((value) {
scanSubscription.cancel();
scanBLE(); //if you need, you can start scan again
});