You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用集成Spotify API:如何配置重定向URI实现跳转?

Flutter集成Spotify API:移动端重定向实现方案

一、先搞定Spotify后台的重定向URI配置

  • iOS:用自定义URL Scheme,比如your-app-scheme://callback,把这个地址加到Spotify开发者后台的「Redirect URIs」列表里。然后去Xcode的Info.plist里配置URL Types,添上对应的Scheme值。
  • Android:同样可以用自定义URL Scheme,比如your-app-scheme://callback,先加到Spotify后台,再去AndroidManifest.xml里给主Activity加个<intent-filter>,专门处理这个Scheme的跳转请求。要是想更规范也能用App Links,但Scheme上手更快。

二、Flutter里的具体实现步骤

  1. 用url_launcher库打开Spotify授权页,参数里带上重定向URI:
    import 'package:url_launcher/url_launcher.dart';
    
    void openSpotifyAuth() async {
      final authUrl = Uri(
        scheme: 'https',
        host: 'accounts.spotify.com',
        path: '/authorize',
        queryParameters: {
          'client_id': '你的Spotify客户端ID',
          'response_type': 'code',
          'redirect_uri': 'your-app-scheme://callback',
          'scope': '需要的权限列表,比如user-read-private user-read-email',
        },
      );
      if (await canLaunchUrl(authUrl)) {
        await launchUrl(authUrl, mode: LaunchMode.externalApplication);
      }
    }
    
  2. 用uni_links库监听重定向回来的链接,提取授权码:
    import 'package:uni_links/uni_links.dart';
    
    void setupLinkListener() async {
      // 处理应用未启动时跳转过来的链接
      final initialUri = await getInitialUri();
      if (initialUri != null) {
        _handleAuthCode(initialUri);
      }
      // 监听应用运行时的跳转链接
      uriLinkStream.listen((Uri? uri) {
        if (uri != null) {
          _handleAuthCode(uri);
        }
      });
    }
    
    void _handleAuthCode(Uri uri) {
      final authCode = uri.queryParameters['code'];
      if (authCode != null) {
        // 拿到code后就可以去请求Spotify的令牌了
        _fetchSpotifyToken(authCode);
      }
    }
    

三、关于localhost的说明

移动端根本用不了localhost,因为手机上没有本地服务器在监听这个地址,必须用自定义URL Scheme或者App Links这种方式,才能让Spotify的授权页面跳回你的Flutter应用。

内容的提问来源于stack exchange,提问作者Bonhart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:50:35