Issue
I’m trying to do a Google Auth operation with Dart Flutter.
I made the exact same code as in the video I watched. While it doesn’t give an error in the video, it gives me an error.
My codes:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class GoogleSignInProvider extends ChangeNotifier {
final googleSignIn = GoogleSignIn();
bool _isSigningIn;
GoogleSignInProvider() {
_isSigningIn = false;
}
bool get isSigningIn => _isSigningIn;
set isSigningIn(bool isSigningIn) {
_isSigningIn = isSigningIn;
notifyListeners();
}
Future login() async {
isSigningIn = true;
final user = await googleSignIn.signIn();
if (user == null) {
isSigningIn = false;
return;
} else {
final googleAuth = await user.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
isSigningIn = false;
}
}
void logout() async {
await googleSignIn.disconnect();
FirebaseAuth.instance.signOut();
}
}
Error:
GoogleSignInProvider GoogleSignInProvider()
package:todolist/google_sign_in.dart
Non-nullable instance field '_isSigningIn' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.
What is the problem? How can I solve it? I thank you in advance for the help.
Solution
because your value is not nullable, it requires a default value
bool _isSigningIn; //non-nullable variable should be inialized
bool? _isSigningIn; //nullable variable and does not requires initialization
If you make your variable nullable you can leave it uninitialized, in other case, you should either initialize it when you define it
bool _isSigningIn = false;
or inside your constructor with a value, like this:
GoogleSignInProvider(this._isSigningIn);
There is one more option, you can also give a default value:
- put your variable in [] and give a default value, it will be positional argument but it won’t be required
See the example below:
class GoogleSignInProvider extends ChangeNotifier {
final googleSignIn = GoogleSignIn();
bool _isSigningIn;
GoogleSignInProvider([this._isSigningIn = false]);
}
Answered By – Prodromos Sarakinou
Answer Checked By – Marilyn (FlutterFixes Volunteer)