英文:
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<void> getCurrentUser() async {
try {
AuthUser user = await Amplify.Auth.getCurrentUser();
if (user.signInDetails is CognitoSignInDetailsApiBased) {
String username = (user.signInDetails as CognitoSignInDetailsApiBased).username;
print("Username: $username");
} else {
print("Unable to retrieve the username.");
}
} on AuthException catch (e) {
safePrint('Error retrieving current user: ${e.message}');
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论