I am Trying to get the gender of a signed in user but I am getting Error like "[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. E/flutter ( 6709): Receiver: null"
//This is My google_signIn_api.dart file
import 'dart:convert';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:http/http.dart' as http;
class GoogleSignInApi {
String url = "https://www.googleapis.com/auth/userinfo.profile";
static final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: ['email', "https://www.googleapis.com/auth/userinfo.profile"]);
static Future<GoogleSignInAccount> login() => _googleSignIn.signIn();
static Future<String> getGender() async {
final headers = await _googleSignIn.currentUser.authHeaders;
final r = await http.get(
Uri.parse(
"https://people.googleapis.com/v1/people/me?personFields=genders&key=******"),
headers: {"Authorization": headers["Authorization"]});
final response = jsonDecode(r.body);
print(response);
return response["genders"][0]["formattedValue"];
}
}
This is the code where I am trying to print the value
Future signIn() async {
final user = await GoogleSignInApi.login();
String gender;
if (user == null) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Sign in Failed')));
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegistrationScreen(user.displayName),
));
// print(user.)
print(user);
gender = await GoogleSignInApi.getGender();
print(user.id);
print(user.email);
print("-------");
print(gender);
print("========");
print(user.displayName);
}
}
CodePudding user response:
this is not unique to flutter, this is universal when interacting with google oauth on any platform
you need to add additional scopes
currently you are only requesting scope for
scopes: ['email', "https://www.googleapis.com/auth/userinfo.profile"]);
You are using https://www.googleapis.com/auth/userinfo.profile
so you r error is not due to scopes. I know this becouse the error message you would have been getting would be
{
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"status": "PERMISSION_DENIED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
"domain": "googleapis.com",
"metadata": {
"method": "google.people.v1.PeopleService.GetPerson",
"service": "people.googleapis.com"
}
}
]
}
}