Experiencing CANCELLED error after Spotify API login in Flutter

I’m facing an issue with the Spotify API in my Flutter application. Although the login appears to be successful, I receive a CANCELLED error during the redirect back to my app.

The authentication seems to work as expected in the browser, but upon redirecting, it shows an error indicating that the user has cancelled the login, even though the login was completed.

Here is the code snippet I’m using for authentication:

class AuthService {
  static const clientId = '//';
  static const clientSecret = '//';
  static const redirectUri = 'myapp://callback';

  static const String authorizationUrl = 'https://accounts.spotify.com/authorize';
  static const String tokenEndPoint = 'https://accounts.spotify.com/api/token';
  static const String userEndpoint = 'https://api.spotify.com/v1/me';

  static Future<String?> authenticate() async {
    final fullAuthUrl =
        '$authorizationUrl?response_type=code&client_id=$clientId&scope=user-read-private user-read-email&redirect_uri=$redirectUri';

    try {
      final response = await FlutterWebAuth.authenticate(
          url: fullAuthUrl, callbackUrlScheme: 'myapp');

      final code = Uri.parse(response).queryParameters['code'];

      if (code != null) {
        return await _getToken(code);
      } else {
         return null;
      }
    } catch (e) {
      if (e.toString().contains('CANCELLED')) {
         print('User has canceled the authentication.');
        return null;
      } else {
        print('An error occurred: $e');
        return null;
      }
    }
  }

  static Future<String?> _getToken(String code) async {
    try {
      final dio = Dio();
      final response = await dio.post(
        tokenEndPoint,
        data: {
          'grant_type': 'authorization_code',
          'code': code,
          'redirect_uri': redirectUri,
        },
        options: Options(
          headers: {
            'Authorization': 'Basic ' + base64Encode(utf8.encode('$clientId:$clientSecret')),
          },
        ),
      );

      if (response.statusCode == 200) {
        return response.data['access_token'];
      } else {
        print('Token retrieval failed: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error occurred while exchanging token: $e');
      return null;
    }
  }

  static Future<Map<String, dynamic>?> fetchProfile(String token) async {
///
}

After the authentication process, I would like to navigate to the main page and display user details. Can anyone help me understand why this issue is occurring?

I encountered a similar issue when implementing Spotify authentication in my Flutter app. The CANCELLED error often occurs due to timing issues with the redirect handling rather than actual user cancellation. In my case, the problem was that the app wasn’t properly registered to handle the custom URL scheme on Android. Make sure you’ve added the intent filter in your AndroidManifest.xml file with the correct scheme. Also, I found that adding a small delay before processing the callback response helped resolve the timing issue. Another thing to check is whether your redirect URI in the Spotify app settings exactly matches what you’re using in the code, including the scheme format. The authentication might complete successfully in the browser, but if the redirect back to your app fails due to scheme registration issues, FlutterWebAuth interprets this as a cancellation.

This happened to me when I was building a music discovery app with Spotify integration. The CANCELLED error typically stems from the FlutterWebAuth package not receiving the proper callback response. What worked for me was ensuring the deep link configuration was correctly set up in both iOS and Android. For iOS, check your Info.plist has the URL scheme properly configured under CFBundleURLTypes. On Android, verify the intent-filter in your main activity includes both the scheme and host. Another issue I ran into was the Spotify developer dashboard settings - the redirect URI must be exactly ‘myapp://callback’ without any trailing slashes or additional parameters. Sometimes clearing the app cache and reinstalling helped resolve persistent callback issues. The authentication completes successfully on Spotify’s end, but the handoff back to your Flutter app fails, causing the package to assume cancellation occurred.

had this exact problem last month! check if your app is getting killed in the background during redirect - android does this sometimes. try setting launchMode to singleTop in your MainActivity and also verify the callback url scheme matches exactly in both code and spotify dashboard settings.