The getter 'uid' was called on null. Receiver: null Tried calling: uid - firebase

this error "
"The getter 'uid' was called on null.Receiver: nullTried calling: uid"
I Faced when i try to sign out from any screen "except home screen" ,
is there any solution for this problem ??
Wrapper :
class Wrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
final user = Provider.of<User_fb>(context);
// return home or login
if (user == null) {
return Login();
} else {
print(user.uid);
return Home();
}
}
}
auth :
Future Signinwithemailandpassword(var Res_email,var Res_Password) async{
try{
UserCredential result= await _auth.signInWithEmailAndPassword(email: Res_email, password: Res_Password);
User user = result.user;
return _userfromfirebase(user);
}catch(e){
return null;
}
}
Future signOut () async{
try{
return await _auth.signOut();
}
catch(e){
print(e.toString());
print("error at signOut ");
return null;
}
}
main :
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(Main());
}
class Main extends StatefulWidget {
#override
_MainState createState() => _MainState();
}
class _MainState extends State<Main> {
#override
Widget build(BuildContext context) {
return StreamProvider<User_fb>.value(
value: Authservice().user,
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Color.fromRGBO(255, 255, 255, 1),
shadowColor: Colors.transparent,
highlightColor: Colors.transparent),
home: Wrapper(),
),
);
}
}
Sign-out button :
ListTile(
leading: Icon(Ionicons.log_out_outline,
color: Color.fromRGBO(86, 197, 150, 1)),
title: Text('Log out'),
onTap: () async {
await _auth.signOut();
},
),
console :
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Br(dirty, dependencies: [_InheritedProviderScope<User_fb>], state: _QrState#24e19):
The getter 'uid' was called on null.
Receiver: null
Tried calling: uid
The relevant error-causing widget was:
Qr file:///G:/AndroidStudioProjects/facem/lib/Screens/Home/Home.dart:687:67
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _QrState.build (package:my_compound/Screens/Qr/qr.dart:99:45)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11)
...

this happens because user is null, So use null check operator.
something like this user?.uid or user.uid ?? '',
TIP: Alway use dart null safety when using flutter.

Related

Another exception was thrown: Null check operator used on a null value!!1

I tried to change the password in app with flutter (Firebase) but it give me and error Another exception was thrown: Null check operator used on a null value. so can someone help me fix this one.
do I need to add something to check null or remove something.
class ChangingPasswordScreen extends StatefulWidget {
static const routeName = '/ChangingPasswordScreen';
//late final String? email;
//final User user;
//ChangingPasswordScreen({required this.user});
#override
State<StatefulWidget> createState() {
return _ChangingPasswordState();
}
}
class _ChangingPasswordState extends State<ChangingPasswordScreen> {
final _formKey = GlobalKey<FormState>();
var newPassword = " ";
final newPasswordController = TextEditingController();
#override
void dispose() {
newPasswordController.dispose();
super.dispose();
}
final currentUser = FirebaseAuth.instance.currentUser;
changePassword() async {
try {
await currentUser!.updatePassword(newPassword);
FirebaseAuth.instance.signOut();
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => SigninScreen(),
),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Your Password has been changed'),
),
);
} catch (error) {}
}
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
setState(() {
newPassword = newPasswordController.text;
});
changePassword();
}
},
child: Text(
'Change Password',
style: TextStyle(fontSize: 18.0),
),
),
In,
await currentUser!.updatePassword(newPassword);
make sure that currentUser is not null before using !. ! indicate that the variable will never be null.
Try something like this,
if(currentUser != null){
try {
await currentUser!.updatePassword(newPassword);
FirebaseAuth.instance.signOut();
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => SigninScreen(),
),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Your Password has been changed'),
),
);
} catch (error) {
print("Error thrown : $error");
}
}
Note: Never leave a catch block empty. Log the error while debugging. Handle the error properly. If you leave a catch block empty, you'll never know if it throws an Exception or not.

Class 'MockFirebaseAuth' has no instance method 'fetchSignInMethodsForEmail' with matching arguments

I can't figure out why I get this error when trying to run this widget test. I just want to mock a user that is in the database so when I type in an email, I either go to my PasswordFormLogin widget if the user email matches the user email that is in the mock user or then go to my RegistrationLoginForm widget.
Debug Console:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞══════════════════════════════════════════════════
The following NoSuchMethodError was thrown running a test:
Class 'MockFirebaseAuth' has no instance method 'fetchSignInMethodsForEmail' with matching
arguments.
Receiver: Instance of 'MockFirebaseAuth'
Tried calling: fetchSignInMethodsForEmail("bob#thebuilder.com")
Found: fetchSignInMethodsForEmail(String) => Future<List<String>>
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 MockFirebaseAuth.noSuchMethod (package:firebase_auth_mocks/src/firebase_auth_mocks_base.dart:70:56)
#2 MockFirebaseAuth.fetchSignInMethodsForEmail (package:firebase_auth/src/firebase_auth.dart:226:24)
#3 ApplicationState.verifyEmail (file:///C:/Users/calvo/Documents/flutter/projects/freegapp/test/LoginFlow_widget_test.dart:92:32)
#4 LoginFlow.build.<anonymous closure> (package:freegapp/LoginFlow.dart:57:45)
#5 _EmailFormState.build.<anonymous closure> (package:freegapp/src/LoginFlowStuff/EmailFormLogin.dart:73:40)
#6 _EmailFormState.build.<anonymous closure> (package:freegapp/src/LoginFlowStuff/EmailFormLogin.dart:64:32)
#7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#8 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
#9 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
#10 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
#11 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
#12 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
#13 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:93:12)
#14 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:138:9)
#15 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
#16 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:136:18)
#17 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:122:7)
#18 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
#19 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
#20 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:287:11)
#21 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#22 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#23 TestWidgetsFlutterBinding.handlePointerEvent (package:flutter_test/src/binding.dart:507:13)
#24 WidgetTester.sendEventToBinding.<anonymous closure> (package:flutter_test/src/widget_tester.dart:792:15)
#25 WidgetTester.sendEventToBinding.<anonymous closure> (package:flutter_test/src/widget_tester.dart:791:39)
#28 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#29 WidgetTester.sendEventToBinding (package:flutter_test/src/widget_tester.dart:791:27)
#30 TestGesture.up.<anonymous closure> (package:flutter_test/src/test_pointer.dart:392:24)
#31 TestGesture.up.<anonymous closure> (package:flutter_test/src/test_pointer.dart:390:39)
#34 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#35 TestGesture.up (package:flutter_test/src/test_pointer.dart:390:27)
#36 WidgetController.tapAt.<anonymous closure> (package:flutter_test/src/controller.dart:278:21)
<asynchronous suspension>
<asynchronous suspension>
(elided 5 frames from dart:async and package:stack_trace)
The test description was:
EmailFormLogin
══════════════════════════════════════════════════════════════════════════════════════════════════
LoginFlow_widget_test.dart:
import 'package:flutter_test/flutter_test.dart';
import 'package:firebase_auth_mocks/firebase_auth_mocks.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:provider/provider.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:freegapp/LoginFlow.dart';
final tUser = MockUser(
isAnonymous: false,
uid: 'T3STU1D',
email: 'bob#thebuilder.com',
displayName: 'Bob Builder',
phoneNumber: '0800 I CAN FIX IT',
photoURL: 'http://photos.url/bobbie.jpg',
refreshToken: 'some_long_token',
);
void main() {
// TextField widgets require a Material widget ancestor.
// In material design, most widgets are conceptually "printed" on a sheet of material. In Flutter's
// material library, that material is represented by the Material widget. It is the Material widget
// that renders ink splashes, for instance. Because of this, many material library widgets require that
// there be a Material widget in the tree above them.
// To introduce a Material widget, you can either directly include one, or use a widget that contains
// Material itself, such as a Card, Dialog, Drawer, or Scaffold.
testWidgets('EmailFormLogin', (WidgetTester tester) async {
await tester.pumpWidget(ChangeNotifierProvider(
create: (context) => ApplicationState(),
builder: (context, _) => MaterialApp(
title: 'Freegap',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Consumer<ApplicationState>(
builder: (context, appState, _) => LoginFlow(
email: appState.email,
loginState: appState.loginState,
startLoginFlow: appState.startLoginFlow,
verifyEmail: appState.verifyEmail,
signInWithEmailAndPassword:
appState.signInWithEmailAndPassword,
cancelRegistration: appState.cancelRegistration,
registerAccount: appState.registerAccount,
signOut: appState.signOut,
key: Key('LoginFlow'))))));
expect(find.byKey(Key('EmailFormLogin')), findsOneWidget);
// Enter 'bob#thebuilder.com' into the TextField.
await tester.enterText(find.byType(TextField), 'bob#thebuilder.com');
await tester.tap(find.byType(ElevatedButton));
expect(find.byKey(Key('EmailFormLogin')), findsOneWidget);
});
}
class ApplicationState extends ChangeNotifier {
ApplicationState() {
init();
}
final auth = MockFirebaseAuth(mockUser: tUser);
Future<void> init() async {
await Firebase.initializeApp();
auth.userChanges().listen((user) {
if (user != null) {
_loginState = ApplicationLoginState.loggedIn;
} else {
_loginState = ApplicationLoginState.loggedOut;
}
notifyListeners();
});
}
ApplicationLoginState _loginState = ApplicationLoginState.loggedOut;
ApplicationLoginState get loginState => _loginState;
String? _email;
String? get email => _email;
void startLoginFlow() {
_loginState = ApplicationLoginState.emailAddress;
notifyListeners();
}
void verifyEmail(
String email,
void Function(FirebaseAuthException e) errorCallback,
) async {
try {
var methods = await auth.fetchSignInMethodsForEmail(email);
if (methods.contains('password')) {
_loginState = ApplicationLoginState.password;
} else {
_loginState = ApplicationLoginState.register;
}
_email = email;
notifyListeners();
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void signInWithEmailAndPassword(
String email,
String password,
void Function(FirebaseAuthException e) errorCallback,
) async {
try {
await auth.signInWithEmailAndPassword(
email: email,
password: password,
);
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void cancelRegistration() {
_loginState = ApplicationLoginState.loggedOut;
notifyListeners();
}
void registerAccount(String email, String displayName, String password,
void Function(FirebaseAuthException e) errorCallback) async {
try {
var credential = await auth.createUserWithEmailAndPassword(
email: email, password: password);
await credential.user!.updateDisplayName(displayName);
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void signOut() {
auth.signOut();
}
}
LoginFlow.dart:
import 'package:flutter/material.dart';
import 'package:freegapp/src/LoginFlowStuff/EmailFormLogin.dart';
import 'package:freegapp/src/LoginFlowStuff/PasswordFormLogin.dart';
import 'package:freegapp/Sell.dart';
import 'package:freegapp/src/LoginFlowStuff/RegisterFormLogin.dart';
import 'package:freegapp/src/style_widgets.dart';
enum ApplicationLoginState {
loggedOut,
emailAddress,
register,
password,
loggedIn,
}
class LoginFlow extends StatelessWidget {
const LoginFlow({
required this.loginState,
required this.email,
required this.startLoginFlow,
required this.verifyEmail,
required this.signInWithEmailAndPassword,
required this.cancelRegistration,
required this.registerAccount,
required this.signOut,
Key? key,
}) : super(key: key);
final ApplicationLoginState loginState;
final String? email;
final void Function() startLoginFlow;
// typedef myFunction = final void Function(String email, void Function(Exception e) error,);
final void Function(
String email,
void Function(Exception e) error,
) verifyEmail; // myFunction verifyEmail() = {}
final void Function(
String email,
String password,
void Function(Exception e) error,
) signInWithEmailAndPassword;
final void Function() cancelRegistration;
final void Function(
String email,
String displayName,
String password,
void Function(Exception e) error,
) registerAccount;
final void Function() signOut;
#override
Widget build(BuildContext context) {
switch (loginState) {
case ApplicationLoginState.loggedOut:
return EmailFormLogin(
key: Key('EmailFormLogin'),
callback: (email) => verifyEmail(
email, (e) => _showErrorDialog(context, 'Invalid email', e)));
case ApplicationLoginState.password:
return PasswordFormLogin(
key: Key('PasswordFormLogin'),
email: email!,
login: (email, password) {
signInWithEmailAndPassword(email, password,
(e) => _showErrorDialog(context, 'Failed to sign in', e));
},
);
case ApplicationLoginState.register:
return RegisterFormLogin(
key: Key('RegisterFormLogin'),
email: email!,
cancel: () {
cancelRegistration();
},
registerAccount: (
email,
displayName,
password,
) {
registerAccount(
email,
displayName,
password,
(e) =>
_showErrorDialog(context, 'Failed to create account', e));
},
);
case ApplicationLoginState.loggedIn:
return Sell(
logout: () {
signOut();
},
key: Key('Sell'),
);
default:
return Row(
children: const [
Text("Internal error, this shouldn't happen..."),
],
);
}
}
}
void _showErrorDialog(BuildContext context, String title, Exception e) {
showDialog<void>(
context: context,
builder: (context) {
return AlertDialog(
title: Text(
title,
style: const TextStyle(fontSize: 24),
),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(
'${(e as dynamic).message}',
style: const TextStyle(fontSize: 18),
),
],
),
),
actions: <Widget>[
StyledButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'OK',
style: TextStyle(color: Colors.deepPurple),
),
),
],
);
},
);
}
EmailFormLogin.dart:
import 'package:flutter/material.dart';
import 'package:freegapp/src/style_widgets.dart';
class EmailFormLogin extends StatefulWidget {
const EmailFormLogin({
required this.callback,
Key? key,
}) : super(key: key);
final void Function(String email) callback;
#override
_EmailFormState createState() => _EmailFormState();
}
class _EmailFormState extends State<EmailFormLogin> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a `GlobalKey<FormState>`,
// not a GlobalKey<_EmailFormState>.
final _formKey = GlobalKey<FormState>(debugLabel: '_EmailFormState');
final _controller = TextEditingController();
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: <Widget>[
Form(
key: _formKey,
child: Column(
children: <Widget>[
const Header('Sign in / Register'),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _controller,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: 'Enter your email',
prefixIcon: Icon(Icons.mail),
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your email address';
}
return null;
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 30),
child: ElevatedButton(
onPressed: () async {
// The FormState class contains the validate() method.
// When the validate() method is called, it runs the validator() function
// for each text field in the form. If everything looks good,
// the validate() method returns true. If any text field contains errors,
// the validate() method rebuilds the form to display any error messages and returns false.
// add ! to assert that it isn’t null (and to throw an exception if it is).
if (_formKey.currentState!.validate()) {
// If the form is valid,
widget.callback(_controller
.text); // call to parent with current string the user is editing
}
},
child: const Text('NEXT'),
),
),
],
),
],
),
),
]));
}
}
The firebase_auth_mocks package currently does not support mocking the fetchSignInMethodsForEmail() method.
A suggestion to get past the error is to replace this line:
var methods = await auth.fetchSignInMethodsForEmail(email);
with something like this:
var methods = await Future.value(['password']);

Home screen showing null future builder in firebaseAuth Flutter

I am currently trying to get the current user state from FirebaseAuth and switch between home screen if user didn't logged out or splash screen if user is logged out. User registration and login are both successful and registered in firestore database. But everytime i closes the application from my phone and re opens, the MediaQuery.of(context) width has a null value and shows an error.
But the bottom navigation bar is still showing. It works when i rebuild the app and login again, it brings me to the home screen. It only occurs when i close and re open the app.
import 'package:country_code_picker/country_localizations.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'routes.dart';
import 'package:screens/home/home_screen.dart';
import 'package:screens/splash/splash_screen.dart';
import 'constants.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
supportedLocales: [Locale('en', 'US')],
localizationsDelegates: [CountryLocalizations.delegate],
title: 'App',
theme: theme(),
routes: routes,
home: LandingPage(),
);
}
}
class LandingPage extends StatelessWidget {
const LandingPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final Future<FirebaseApp> _init = Firebase.initializeApp();
return FutureBuilder(
future: _init,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Scaffold(
body: Center(
child: Text("Error: ${snapshot.error}"),
),
);
}
if (snapshot.connectionState == ConnectionState.done) {
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, streamSnapshot) {
if (streamSnapshot.hasError) {
return Scaffold(
body: Center(
child: Text("Error: ${streamSnapshot.error}"),
),
);
}
if (streamSnapshot.connectionState == ConnectionState.active) {
print(streamSnapshot.data.toString());
if (streamSnapshot.data == null) {
return SplashScreen();
} else {
return HomeScreen();
}
}
return Scaffold(
body: Center(
child: CircularProgressIndicator(
backgroundColor: Colors.white,
color: kPrimaryColor,
strokeWidth: 3,
),
),
);
},
);
}
return Scaffold(
body: Center(
child: CircularProgressIndicator(
backgroundColor: Colors.white,
color: kPrimaryColor,
strokeWidth: 3,
),
),
);
},
);
}
}
Maybe i thought its a problem with the future builder or stream builder? Any of you have a solution for this problem or another way to implement it.
Launching lib/main.dart on STK L21 in debug mode...
✓ Built build/app/outputs/flutter-apk/app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:33019/yIPGCqY2gwY=/ws
I/flutter ( 4249): locale.languageCode: en
D/AwareBitmapCacher( 4249): handleInit switch not opened pid=4249
I/flutter ( 4249): User(displayName: , email: rohanbhautoo#gmail.com, emailVerified: false, isAnonymous: false, metadata: UserMetadata(creationTime: 2021-06-10 08:20:44.583, lastSignInTime: 2021-06-10 15:50:23.573), phoneNumber: , photoURL: null, providerData, [UserInfo(displayName: , email: rohanbhautoo#gmail.com, phoneNumber: , photoURL: null, providerId: password, uid: rohanbhautoo#gmail.com)], refreshToken: , tenantId: null, uid: yviaYOJ5ziayFQhvhvemB3MjkPr1)
════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building Body(dirty):
Null check operator used on a null value
The relevant error-causing widget was
Body
When the exception was thrown, this was the stack
#0 getProportionateScreenWidth
#1 Body.build
#2 StatelessElement.build
#3 ComponentElement.performRebuild
#4 Element.rebuild
...
════════════════════════════════════════════════════════════════════════════════
Size_config.dart
import 'package:flutter/material.dart';
class SizeConfig {
static MediaQueryData? _mediaQueryData;
static double? screenWidth;
static double? screenHeight;
static double? defaultSize;
static Orientation? orientation;
void init(BuildContext context) {
_mediaQueryData = MediaQuery.of(context);
screenWidth = _mediaQueryData!.size.width;
screenHeight = _mediaQueryData!.size.height;
orientation = _mediaQueryData!.orientation;
}
}
// Proportionate height per screen size
double getProportionateScreenHeight(double inputHeight) {
double? screenHeight = SizeConfig.screenHeight;
return (inputHeight / 812.0) * screenHeight!;
}
// Proportionate width per screen size
double getProportionateScreenWidth(double inputWidth) {
double? screenWidth = SizeConfig.screenWidth;
return (inputWidth / 375.0) * screenWidth!;
}
The stacktrace line for #0 is return (inputWidth / 375.0) * screenWidth!; It is showing that im using a null check on screenWidth!.
I don't see where you actually call SizeConfig().init(context) ?
Nothing gets defined for you until that happens at the top of your project.
I guess the culprit is this line:
print(streamSnapshot.data.toString());
You are actually checking that streamSnapshot.data is null on the next line:
print(streamSnapshot.data.toString());
if (streamSnapshot.data == null) {
return SplashScreen();
} else {
return HomeScreen();
}

Asynchronous Function Error In Dart-Flutter

So I'm trying to create a simple Sign In page in Flutter using Google Firebase but Firebase is not giving me desired output. Maybe its error in Asynchronous Function cause its giving me output Instance of 'Future<dynamic>'
Code for Anonymously Sign In dart file:
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future signAnonymous() async {
try {
AuthResult result = await _auth.signInAnonymously();
FirebaseUser user = result.user;
return user;
} catch (e) {
print(e.toString());
return null;
}
}
}
Sign In Page Code:
import 'package:flutter/material.dart';
import 'package:freezeria/Screens/services/auth.dart';
class signin extends StatefulWidget {
#override
_signinState createState() => _signinState();
}
class _signinState extends State<signin> {
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.purple[300],
appBar: AppBar(
backgroundColor: Colors.purple[600],
elevation: 0.0,
centerTitle: true,
title: Text('Sign In To Freezeria!'),
),
body: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
child: ElevatedButton(
child: Text('SignIn'),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(Colors.purple[100]),
),
onPressed: () async {
dynamic result = _auth.signAnonymous();
if (result == null) {
print("Error Signing In");
} else {
print('Signed In');
print(result);
}
}
)
),
);
}
}
The Output I got was:
I/flutter ( 8533): Signed In
I/flutter ( 8533): Instance of 'Future<dynamic>'
I need to get user details provided by the firebase
Any help will be appreciated :)
_auth.signAnonymous() is an async function, for that matter it returns a Future ! Use the await keyword to get the user value instead of a Future object !
result = await _auth.signAnonymous();

Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe - Flutter

Have anybody encounter this issue before?
E/flutter (12975): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter (12975): At this point the state of the widget's element tree is no longer stable.
E/flutter (12975): 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.
Upon googling I found out that it has something to do with context? That is why I passed the context via argument of a function
Below is the code
class CustRegView extends StatefulWidget {
#override
_CustRegViewState createState() => _CustRegViewState();
}
class CustRegView extends StatelessWidget{
final TextEditingController _controller = TextEditingController();
#override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return BaseView<CustRegViewModel>(
builder: (context, model, child) => Scaffold(
...<some code>
FlatButton (
onPressed: () async {
var registerSuccess = await model.register( _controller.text);
if (registerSuccess) {
Navigator.pushNamed(context, 'newScreen'); <--- E R R O R H E R E } else {
UIHelper().showErrorButtomSheet(context, model.errorMessage);
}
)
}
CustRegViewModel looks like this
class CustRegViewModel extends BaseViewModel {
final AuthService _authService = locator<AuthService>();
final DialogService _dialogService = locator<DialogService>();
dynamic verifiedUserID ;
Future<bool> register(String phoneNo) async {
verifiedUserID = await verifyPhone(updatedPhoneNo);
return verifiedUserID != null ? true : false; // From here it
// returns true
}
Future<void> verifyPhone(phoneNo) async {
var completer = Completer<dynamic>();
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: updatedPhoneNo,
timeout: Duration(seconds: 50),
verificationCompleted: (AuthCredential authCred) async {...... <some code>
verificationFailed: (AuthException authException) {...... <some code>
codeSent: (String verID, [int forceCodeResend]) async {...... <some code>
codeAutoRetrievalTimeout: (String verID) {...
).catchError((error) {...... <some code>
return completer.future;
}
}
main class looks like this
void main() {
setupLocator();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final GlobalKey<NavigatorState> navigatorKey =
new GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
return StreamProvider<User>(
initialData: User.initial(),
create: (BuildContext context) => locator<AuthService>().user,
child: MaterialApp(
builder: (context, widget) => Navigator(
onGenerateRoute: (settings) => MaterialPageRoute(
builder: (context) => DialogManager(
child: widget,
),
),
),
title: 'Fitness Diet',
theme: ThemeData(),
initialRoute: 'splash',
navigatorKey: navigatorKey,
onGenerateRoute: Router.generateRoute,
),
);
}
}

Resources