Handling Spotify OAuth redirect issues with flutter_web_auth package

I’m working on a Flutter app that needs to authenticate with Spotify using the flutter_web_auth package. Everything seems configured correctly but I’m running into routing problems when the auth flow returns to my app.

Here’s my basic setup:

import 'package:flutter/material.dart';
import 'package:flutter_web_auth/flutter_web_auth.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:myapp/config.dart';

void main() async {
  await dotenv.load();
  runApp(const MusicApp());
}

class MusicApp extends StatelessWidget {
  const MusicApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Music Player',
      routes: {
        "/": (context) => const MainScreen(),
      },
    );
  }
}

class MainScreen extends StatelessWidget {
  const MainScreen({Key? key}) : super(key: key);
  
  void handleAuth() async {
    var authUrl = Uri.https('accounts.spotify.com', '/authorize', {
      'client_id': Config.spotifyClientId,
      "response_type": "code",
      "redirect_uri": Config.redirectUrl, // "musicapp://"
      "scope": [].join(" "),
      "show_dialog": "true",
    });

    final authResult = await FlutterWebAuth.authenticate(
      url: authUrl.toString(),
      callbackUrlScheme: Config.urlScheme, // "musicapp"
    );

    print(authResult);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [Text("Welcome")],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: handleAuth,
        child: const Icon(Icons.music_note),
      ),
    );
  }
}

My AndroidManifest.xml configuration:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.musicapp">
  <uses-permission android:name="android.permission.INTERNET" />
  <queries>
    <intent>
      <action android:name="android.intent.action.VIEW" />
      <data android:scheme="https" />
    </intent>
  </queries>
  <application android:label="musicapp" android:icon="@mipmap/ic_launcher">
    <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize">
      <meta-data android:name="flutter_deeplinking_enabled" android:value="true" />
      <intent-filter android:label="flutter_web_auth" android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="musicapp" />
      </intent-filter>
    </activity>
  </application>
</manifest>

The problem is when Spotify redirects back to my app, I get this error:

Could not navigate to initial route.
The requested route name was: "/?code=yyyyyyyyyy"
There was no corresponding route in the app, and therefore the initial route specified will be ignored and "/" will be used instead.

It seems like the app is trying to navigate to a route that includes the authorization code parameter, but my routes don’t handle this. How should I properly handle the OAuth callback with the authorization code? Any ideas on what I’m missing in my setup?

Had this exact problem last week! Flutter’s router grabs the callback before flutter_web_auth can handle it. Add android:exported="true" to your activity in the manifest - that’s what fixed it for me. Also check you’re not running other routing packages that mess with the oauth flow.

This happens because Flutter’s web deep linking tries to handle the OAuth callback like a normal route. I had the same issue with Spotify integration on my last project. Fixed it by modifying MainActivity to handle the custom scheme before Flutter’s routing kicks in. Override the intent handling in MainActivity.kt to catch the musicapp:// scheme and let flutter_web_auth process it directly. Also double-check your redirect URI in the Spotify dashboard matches your scheme exactly - I wasted hours debugging because I had a trailing slash mismatch. flutter_web_auth should intercept the callback before it hits Flutter’s router, so this error means your intent filtering isn’t working right.

This is a common issue with OAuth in Flutter. It appears that the flutter_web_auth package is treating your callback URL as a standard route, which your router isn’t configured to handle. I’ve encountered this issue before, and here’s how I resolved it. First, try removing the flutter_deeplinking_enabled line from your AndroidManifest.xml, as it can interfere with flutter_web_auth’s handling of callbacks. Secondly, ensure that your Config.redirectUrl aligns perfectly with the one specified in your Spotify application settings, as even small discrepancies can disrupt the routing process. When configured correctly, flutter_web_auth should be able to manage the callback automatically without invoking conventional Flutter routing.