尽管我是新手,我如何获得性别,年龄,年龄在我的flutter应用程序中的API中

发布于 2025-01-29 11:04:05 字数 1817 浏览 5 评论 0原文

我正在尝试获得用户签名的性别,但是我会遇到错误,例如“ [错误:flutter/lib/ui/ui_dart_state.cc(198)]未手持的例外:nosuchmethoderror:nosuchmethoderror:方法'[] []在null上被称为null上。 。 E/Flutter(6709):接收器:null”

//这是我的Google_signin_api.dart文件

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"];
  }
}

这是我试图打印值的代码

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);
    }
  }

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);
    }
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故乡的云 2025-02-05 11:04:05

这并不是颤抖的独特之处,当

在任何平台上与Google Oauth进行交互时,

scopes: ['email', "https://www.googleapis.com/auth/userinfo.profile"]);

这是通用oauth2/scopes“ rel =“ nofollow noreferrer”> https://developers.google.com/indesity/protocols/oauth2/scopes

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"]);

https://developers.google.com/identity/protocols/oauth2/scopes

简美 2025-02-05 11:04:05

错误:flutter/lib/ui/ui_dart_state.cc(198)]未经手的例外:nosuchmethoderror:方法'[]'在null上称为null。 E/Flutter(6709):接收器:null“

表示您正在尝试从当前null的值重新qust数据。

如果用户尚未添加性别,则响应[“ genders”] [0] [0] 来索取null值

代码>将通过响应[“ genders

”] [0] [ 说明您的范围是您的范围

。 people/api/rest/v1/people/get“ rel =“ nofollow noreferrer”> people.get 在文档中列出了使用哪种范围。在这种情况下,其中之一

您正在使用https://www.googleapis.com/auth/userinfo.profile,因此您的错误不是范围。我知道这是因为您将收到的错误消息将是

{
  "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"
        }
      }
    ]
  }
}

ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. E/flutter ( 6709): Receiver: null"

Means that you are trying to requst data from a value that is currently null.

If the user has not added a gender then response["genders"][0] will be null so trying to request data from a null value by doing response["genders"][0]["formattedValue"];

Will result in a NoSuchMethodError error.

Clarification

Another answer was posted stating that your issue is with your scopes. I want to be user you understand that this is not the issue.

Each method in this case people.get lists in the documentation what scope are required to use it. In this case one of these

enter image description here

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"
        }
      }
    ]
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文