首页 > 解决方案 > Dart/Flutter 错误:“AuthSession”类型的值不能分配给“CognitoAuthSession”类型的变量

问题描述

我们的应用程序需要从Cognito获取用户角色,为了解决这个问题,我们遵循了this 注释,但linter(来自Android Studio)和运行时间向我们展示了下一个错误:

[+10900 ms] [+10852 ms] lib/auth/infrastructure/auth.repository.dart:61:43: Error: A value of type 'AuthSession' can't be assigned to a variable of type 'CognitoAuthSession'.
[   +3 ms] [   +2 ms]  - 'AuthSession' is from 'package:amplify_auth_plugin_interface/src/Session/AuthSession.dart' ('/opt/flutter/.pub-cache/hosted/pub.dartlang.org/amplify_auth_plugin_interface-0.1.1/lib/src/Session/AuthSession.dart').
[        ] [        ]  - 'CognitoAuthSession' is from 'package:amplify_auth_cognito/src/CognitoSession/CognitoAuthSession.dart' ('/opt/flutter/.pub-cache/hosted/pub.dartlang.org/amplify_auth_cognito-0.1.1/lib/src/CognitoSession/CognitoAuthSession.dart').
[        ] [        ]       CognitoAuthSession fetchedSession = await _authCategory.fetchAuthSession(
[        ] [        ]                                           ^

接下来是我们使用Amplify Auth的存储库代码:

import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_flutter/amplify.dart';
import 'package:amplify_flutter/categories/amplify_categories.dart';

class AmplifyAuthRepository implements AuthRepository {
  AmplifyAuthRepository({AuthCategory? authCategory})
      : _authCategory = authCategory ?? Amplify.Auth;

  final AuthCategory _authCategory;

@override
  Future<Map<String, dynamic>> fetchSession() async {
    try {
      CognitoAuthSession fetchedSession = await _authCategory.fetchAuthSession(
          options: CognitoSessionOptions(getAWSCredentials: true));
      String token = fetchedSession.userPoolTokens.idToken;
      Map<String, dynamic> payload = Jwt.parseJwt(token);
      // Access the groups
      List groups = payload['cognito:groups'];
      Map<String, dynamic> result = {
        'isSignedIn': fetchedSession.isSignedIn,
        'roles': groups
      };
      return result;
    } on AmplifyException catch (error) {
      // TODO: Catch error for analytics, not required for frontend.
      throw AmplifyException(error.toString());
    }
  }
}

它必须是一个CognitoAuthSession类型变量才能提取会话令牌并使用它来获取用户的角色(如您在上述评论中所见)。

有关详细信息,请访问此问题

Flutter (Channel stable, 2.0.4, on Linux, locale en_US.UTF-8)
  • Flutter version 2.0.4 at /opt/flutter
  • Framework revision b1395592de (7 days ago), 2021-04-01 14:25:01 -0700
  • Engine revision 2dce47073a
  • Dart version 2.12.2

我可能用错了吗?

谢谢。

标签: flutterdartamazon-cognitoaws-amplify

解决方案


强制转换等待 _authCategory.fetchAuthSession 对 CognitoAuthSession 的响应。

CognitoAuthSession fetchedSession =
        await _authCategory.fetchAuthSession(options: CognitoSessionOptions(getAWSCredentials: true)) as CognitoAuthSession;
    print('fetchedSession ${fetchedSession.userPoolTokens?.idToken}');

推荐阅读