How to log out user and How to check user verify mail - flutter

I got the following problem.
When user register he will be on a page, where I show a message like check your Email account. And when user check his account and confirm his mail he automatically get to homepage. So far so good. But when user press register button an get mail and reload the page he get also inside homepage without confirm his mail.
I trie this
Future<String> signIN(String email, String password) async {
try {
UserCredential result =await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email.trim(),
password: password,
);
User user = result.user;
if(user.emailVerified){
return user.uid;
}
} on FirebaseAuthException catch (e) {
but not working.
here's my verify email page
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
class VerifyScreen extends StatefulWidget {
#override
_VerifyScreenState createState() => _VerifyScreenState();
}
class _VerifyScreenState extends State<VerifyScreen> {
final auth= FirebaseAuth.instance;
User user;
Timer timer;
#override
void initState() {
user= auth.currentUser;
user.sendEmailVerification();
timer= Timer.periodic(Duration(seconds: 5), (timer) {
checkEmailverifyed();
});
super.initState();
}
#override
void dispose() {
timer.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
)
);
}
Future<void> checkEmailverifyed() async{
user=auth.currentUser;
await user.reload();
if(user.emailVerified){
timer.cancel();
Navigator.of(context).
pushReplacement(MaterialPageRoute(builder:(context)=> Homepage()));
}
}
}
Maybe anyone can help.
And also when user press logout button nothing happened. but when user restart the app he logged out.
here's my logout pressed method:
onPressed: () {
FirebaseAuth.instance.signOut();
FirebaseAuth.instance.signOut();Navigator.pushNamedAndRemoveUntil(context, LoginScreen.route, (route) => false);
Heres the error of the sign out:
D/FirebaseAuth(26776): Notifying id token listeners about a sign-out event.
D/FirebaseAuth(26776): Notifying auth state listeners about a sign-out event.
E/flutter (26776): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Could not find a generator for route RouteSettings("SignIn", null) in the _WidgetsAppState.
E/flutter (26776): Make sure your root app widget has provided a way to generate
E/flutter (26776): this route.
E/flutter (26776): Generators for routes are searched for in the following order:
E/flutter (26776): 1. For the "/" route, the "home" property, if non-null, is used.
E/flutter (26776): 2. Otherwise, the "routes" table is used, if it has an entry for the route.
E/flutter (26776): 3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
E/flutter (26776): 4. Finally if all else fails onUnknownRoute is called.
E/flutter (26776): Unfortunately, onUnknownRoute was not set.
E/flutter (26776): #0 _WidgetsAppState._onUnknownRoute.<anonymous closure> (package:flutter/src/widgets/app.dart:1219:9)
E/flutter (26776): #1 _WidgetsAppState._onUnknownRoute (package:flutter/src/widgets/app.dart:1234:6)
E/flutter (26776): #2 NavigatorState._routeNamed (package:flutter/src/widgets/navigator.dart:4148:37)
E/flutter (26776): #3 NavigatorState.pushNamedAndRemoveUntil (package:flutter/src/widgets/navigator.dart:4391:34)
E/flutter (26776): #4 Navigator.pushNamedAndRemoveUntil (package:flutter/src/widgets/navigator.dart:2042:34)
E/flutter (26776): #5 _openSignOutDrawer.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:projectandroidstudiodenya/seitenleiste/seitenleiste.dart:188:90)
E/flutter (26776): #6 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (26776): #7 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (26776): <asynchronous suspension>
E/flutter (26776):
And the error of the sig in:
E/flutter (26776): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The getter 'emailVerified' was called on null.
E/flutter (26776): Receiver: null
E/flutter (26776): Tried calling: emailVerified
E/flutter (26776): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (26776): #1 AuthService.signIN (package:projectandroidstudiodenya/services/auth.dart:44:44)
E/flutter (26776): #2 _LoginScreenState._buildLoginBtn.<anonymous closure> (package:projectandroidstudiodenya/authenticate/signin.dart:170:48)
E/flutter (26776): #3 _LoginScreenState._buildLoginBtn.<anonymous closure> (package:projectandroidstudiodenya/authenticate/signin.dart:168:24)
E/flutter (26776): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:994:20)
E/flutter (26776): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (26776): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
E/flutter (26776): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter (26776): #8 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:267:7)
E/flutter (26776): #9 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
E/flutter (26776): #10 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:443:20)
E/flutter (26776): #11 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter (26776): #12 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:288:11)
E/flutter (26776): #13 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter (26776): #14 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter (26776): #15 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter (26776): #16 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter (26776): #17 _rootRunUnary (dart:async/zone.dart:1370:13)
E/flutter (26776): #18 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (26776): #19 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (26776): #20 _invoke1 (dart:ui/hooks.dart:186:10)
E/flutter (26776): #21 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter (26776): #22 _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)
E/flutter (26776):
My sig in method looks like that:
Future<String> signIN(String email, String password) async {
try {
if(FirebaseAuth.instance.currentUser.emailVerified) {
( await _auth.signInWithEmailAndPassword(
email: email.trim(), password: password,)).user;
// User user = result.user;
}
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
}
}
return null;
}
It looks different because I changed it like it was before that so I can check if maybe it was on the changes it do because it runs at this point.

You should check email verification within you're sign-in method, and if the email was verified then return instance.signInWithEmailAndPassword.
full code:
Future<String> signIN(String email, String password) async {
try {
if(FirebaseAuth.instance.currentUser.emailVerified) {
( await _auth.signInWithEmailAndPassword(
email: email.trim(), password: password,)).user;
return "success";
// User user = result.user;
}
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
}
}
return return "error";;
}
so every moment when signIN calling it would check email verification and if it verified it would work if it isn't it will return "error" or other problem variants, and you can listen to response so when it gives you an error you should return a snackBar, if it returns "success" then you would navigate.
Solution of logout issue:
onPressed: () {
FirebaseAuth.instance.signOut().then((){
Navigator.pushNamedAndRemoveUntil(context, LoginScreen.route (route) => false);
});

Related

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

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

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

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

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),
),
),
);
}
}

Flutter app not initializing Firebase instance

I am creating a Flutter app that uses Google Authentication in Firebase.
The user can sign in with Google, but I need to keep the user logged in when the user launches the app again.
This is my code for main.dart
import 'package:flutter/material.dart';
import 'login_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> _checkUserStatusGoogle() async {
await Firebase.initializeApp();
_auth
.authStateChanges()
.listen((User user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
}
#override
void initState() {
Firebase.initializeApp().whenComplete(() {
_checkUserStatusGoogle().then((value) {
print('Check done done');
});
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Login',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(),
);
}
}
There is an error when launching the app with this code:
E/flutter (15566): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
E/flutter (15566): #0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
E/flutter (15566): #1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
E/flutter (15566): #2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
E/flutter (15566): #3 new MyApp (package:flutter_faro_turnos/main.dart:10:43)
E/flutter (15566): #4 main (package:flutter_faro_turnos/main.dart:6:23)
E/flutter (15566): #5 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:233:25)
E/flutter (15566): #6 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (15566): #7 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (15566): #8 _runZoned (dart:async/zone.dart:1630:10)
E/flutter (15566): #9 runZonedGuarded (dart:async/zone.dart:1618:12)
E/flutter (15566): #10 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:225:5)
E/flutter (15566): #11 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
E/flutter (15566): #12 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
What is wrong in my code?
EDIT:
New main.dart code:
import 'package:flutter/material.dart';
import 'login_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> _checkUserStatusGoogle() async {
print('User is currently signed out!');
FirebaseAuth.instance
.authStateChanges()
.listen((User user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
}
#override
void initState() {
print ("estoy en initstate");
Firebase.initializeApp().whenComplete(() {
_checkUserStatusGoogle().then((value) {
print('Check done done');
});
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Login',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(),
);
}
}
New error output:
E/flutter (18393): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
E/flutter (18393): If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
E/flutter (18393): If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
E/flutter (18393): #0 defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:93:7)
E/flutter (18393): #1 defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:106:4)
E/flutter (18393): #2 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:145:62)
E/flutter (18393): #3 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:151:35)
E/flutter (18393): #4 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter (18393): #5 MethodChannel.invokeListMethod (package:flutter/src/services/platform_channel.dart:347:40)
E/flutter (18393): #6 MethodChannelFirebase._initializeCore (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:30:36)
E/flutter (18393): #7 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:75:13)
E/flutter (18393): #8 Firebase.initializeApp (package:firebase_core/src/firebase.dart:43:25)
E/flutter (18393): #9 main (package:flutter_faro_turnos/main.dart:7:18)
E/flutter (18393): #10 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:233:25)
E/flutter (18393): #11 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (18393): #12 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (18393): #13 _runZoned (dart:async/zone.dart:1630:10)
E/flutter (18393): #14 runZonedGuarded (dart:async/zone.dart:1618:12)
E/flutter (18393): #15 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:225:5)
E/flutter (18393): #16 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
E/flutter (18393): #17 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (18393):
V/FA (18393): Inactivity, disconnecting from the service
This line of code is executing in during the construction of MyApp, before any of its methods are called:
final FirebaseAuth _auth = FirebaseAuth.instance
Since initializeApp() hasn't been invoked yet, this fails and throws the exception. You should consider calling initializeApp() during main instead, as shown here. The post gives several options. Personally, I would use main().
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
You only need the one call to initializeApp() when your app starts, so you should also remove the other calls in your code.