I have seen various questions about the same topic, and realized that ‘currentUser’ does not go with future after the update in FirebaseAuth
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<void> _logout() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e.toString());
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Phone Auth Demo"),
backgroundColor: Colors.cyan,
),
body: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (context, snapshot) {
final firebaseUser = snapshot.data;
return snapshot.hasData
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"SignIn Success 😊",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
SizedBox(
height: 20,
),
Text("UserId:${firebaseUser.uid}"),
SizedBox(
height: 20,
),
Text(
"Registered Phone Number: ${firebaseUser.phoneNumber}"),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: _logout,
child: Text(
"LogOut",
style: TextStyle(color: Colors.white),
),
color: Colors.cyan,
)
],
),
)
: CircularProgressIndicator();
},
),
);
}
}
future: FirebaseAuth.instance.currentUser(),
- this line is the error. It shows this error:
- The function can’t be unconditionally invoked because it can be
‘null’. (Documentation) Try adding a null check (‘!’).
Also, have some errors in uid and phoneNumber
- There I have this error:
- The property ‘phoneNumber’ can’t be unconditionally accessed
because the receiver can be ‘null’. (Documentation) Try making
the access conditional (using ‘?.’) or adding a null check to the
target (‘!’).
3
Answers
just add
await FirebaseAuth.instance!.signOut();
orawait FirebaseAuth!.instance.signOut();
this is not exactly an error, latest version of flutter and dart introduce the null checker so whenever you are getting value you may need to add!
or?
and also when you initialize blank variable you may need to addlate
or?
. You can learn more from here https://dart.dev/null-safety. And if you wish to remove this feature just downgrade yourin
pubspec.yaml
While you are using
RaisedButton
I will suggest you to update the flutter version. Now for getting current user, you dont need to use FutureBuilder, But make sure to initialize the Firebase on main method.You will get the current user with
FirebaseAuth.instance.currentUser
, it can return null,Here is the modification I’ve made,
check like that need to check null,
for more info see documentation
https://firebase.google.com/docs/auth/flutter/manage-users