从对象实例中提取元素的值

huangapple go评论62阅读模式
英文:

Extract value of an element from object instance

问题

如何只获取上面的"username"元素值?

英文:

Here is my code to get the current users phone number.

  Future<void> getCurrentUser() async {
    try {
      AuthUser user = await Amplify.Auth.getCurrentUser();
      print(user.signInDetails);
    } on AuthException catch (e) {
      safePrint('Error retrieving current user: ${e.message}');
    }
  }

The print statement above which extracts the values of the signInDetails array, does not allow me to go deeper one more level. Here is result if I just print the object instance -

CognitoSignInDetailsApiBased {
I/flutter (19338):   "signInType": "apiBased",
I/flutter (19338):   "username": "+14160000000",
I/flutter (19338):   "authFlowType": "USER_SRP_AUTH"
I/flutter (19338): }

How do I just get the value of username element above.

答案1

得分: 1

根据您发布的文档AuthUser#signInDetails 返回一个SignInDetails的实例,该实例在这里有文档说明。看起来没有一个名为username的访问器,但有一个toJson()方法,该方法返回一个映射。因此,您应该能够通过print(user.signInDetails.toJson()['username'])仅打印用户名值。

英文:

According to the docs you posted, AuthUser#signInDetails returns an instance of SignInDetails, documented here. It looks like there isn't an accessor username, but there is a toJson() method that returns a map. Given that, you should be able to print just the username value via print(user.signInDetails.toJson()['username'])

答案2

得分: 1

你可以这样做:

Future<void> getCurrentUser() async {
  try {
    AuthUser user = await Amplify.Auth.getCurrentUser();

    if (user.signInDetails is CognitoSignInDetailsApiBased) {
      String username = (user.signInDetails as CognitoSignInDetailsApiBased).username;

      print("用户名:$username");
    } else {
      print("无法检索到用户名。");
    }
  } on AuthException catch (e) {
    safePrint('检索当前用户时出错:${e.message}');
  }
}

CognitoSignInDetailsApiBased 类

英文:

You can do this:

Future&lt;void&gt; getCurrentUser() async {
  try {
    AuthUser user = await Amplify.Auth.getCurrentUser();

    if (user.signInDetails is CognitoSignInDetailsApiBased) {
      String username = (user.signInDetails as CognitoSignInDetailsApiBased).username;

      print(&quot;Username: $username&quot;);
    } else {
      print(&quot;Unable to retrieve the username.&quot;);
    }
  } on AuthException catch (e) {
    safePrint(&#39;Error retrieving current user: ${e.message}&#39;);
  }
}

CognitoSignInDetailsApiBased class

huangapple
  • 本文由 发表于 2023年7月13日 11:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定