I am new to flutter and trying to integrate flutter and firebase. I created a flutter project and added the android and ios app and then downloaded the files to the flutter app. But when I run the project I am getting the following error
Exception has occurred.LateError (LateInitializationError: Local 'firebaseUser' has not been initialized.)
What may be the reason? These are the lines of code
Future<bool> signInAnonymously() async {
if (Configurations.shared.isThisVersionTestedInAppStore ||
Utils.isInDebugMode!) {
late UserCredential firebaseUser;
try {
firebaseUser = await FirebaseAuth.instance.signInAnonymously();
} catch (e) {
AppLogger.error(e);
}
return didLogInSuccessfully(withUser: firebaseUser.user);
} else {
return false;
}}
main.dart file contents
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await Configurations.shared.init();
await Repository.shared.init();
runApp(Configurations.shared.getMainAppWidget());
runTestScripts();
}
void runTestScripts() {
Utils.test();
Synchronizer.test();
Localized.test();
}
CodePudding user response:
Did you add these lines at main.dart
to make sure the firebase starts before the app launches.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const ChatApp());
}
CodePudding user response:
You're getting the error because you are attempting to use the firebaseUser
variable without initializing it.
This is because firebaseUser
did not get a value in the line below:
firebaseUser = await FirebaseAuth.instance.signInAnonymously();
Since the firebaseUser
variable can be null, you can change it from a late
variable to a nullable
variable like this:
Change this:
late UserCredential firebaseUser;
to this:
UserCredential? firebaseUser;
And update your return statement from this:
return didLogInSuccessfully(withUser: firebaseUser.user);
to this:
return didLogInSuccessfully(withUser: firebaseUser?.user);
This only calls the .user
property on firebaseUser
if the variable is not null.
Your updated code should be this:
Future<bool> signInAnonymously() async {
if (Configurations.shared.isThisVersionTestedInAppStore ||
Utils.isInDebugMode!) {
UserCredential? firebaseUser;
try {
firebaseUser = await FirebaseAuth.instance.signInAnonymously();
} catch (e) {
AppLogger.error(e);
}
return didLogInSuccessfully(withUser: firebaseUser?.user);
} else {
return false;
}
}