Orientação gerada a partir de informações públicas. Apenas para referência.
O pacote spotify_sdk é um plugin do Flutter que permite a integração com o SDK do Spotify e a biblioteca de autenticação, permitindo que desenvolvedores interajam com os serviços de música do Spotify em seus aplicativos Flutter. Ele facilita a autenticação do usuário, o controle de reprodução e o acesso aos ricos dados musicais do Spotify. Projetado para comunicação fluida com as APIs do Spotify, simplifica a incorporação de funcionalidades de música em aplicativos. O plugin oferece suporte às plataformas Android e iOS, embora possa ser necessário configuração específica por plataforma. É mantido por tobibusch.dev e hospedado no GitHub para contribuições da comunidade.
Casos de uso
Integrar login e autenticação do Spotify
Controlar a reprodução de música no aplicativo
Exibir as playlists e faixas do usuário
Construa recursos de descoberta musical
Habilite o compartilhamento de músicas do aplicativo
Sincronizar o estado de reprodução entre dispositivos
Principais recursos
Autenticação OAuth2 do Spotify
Controle de reprodução (reproduzir/pausar/procurar)
Acesso ao perfil do usuário e às playlists
Suporte para metadados de faixa e álbum
Atualizações em tempo real do estado de reprodução
Compatibilidade multiplataforma
Indicado para
Aplicativos de streaming de música
Integrações de player de podcast
Recursos de compartilhamento de música social
Construtores de playlists personalizadas
Prototipagem de desenvolvedor com Spotify
Aplicativos que exigem sincronização de música offline
Considerações
Requer conta de desenvolvedor do Spotify
É necessário o registro adequado do aplicativo no Painel do Spotify
Configurações específicas da plataforma necessárias
Limitado às permissões de escopo da API do Spotify
Pode exigir manipulação adicional para reprodução em segundo plano
Depende de SDKs externos do Spotify para funcionalidade completa
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
spotify_sdk
Description
This is a flutter package that wraps the native iOS and Android Spotify "remote" SDKs as well as the Spotify Web Playback SDK for web. Since it wraps the native SDKs it has the same features and limitations.
[!IMPORTANT]
Upgrading to 4.0.0? Check out the 4.0.0 Migration Guide for important migration instructions regarding Android zero-configuration setup, Spotify Android Auth SDK v5.0.0 manifest registration, and typed SpotifyException domain error handling.
Setup
Android
This package uses both the Spotify App Remote SDK and the Spotify Authentication Library.
Register your app in the Spotify Developer Portal. Add your package name, a SHA-1 fingerprint of your signing certificate, and a Redirect URI in the app settings on the dashboard.
Register the Redirect Activity: Inside the <application> tag of your android/app/src/main/AndroidManifest.xml file, declare the RedirectUriReceiverActivity (note the .browser. in the package path required by Spotify Auth SDK v5.0.0):
[!WARNING]
You must use the exact class name com.spotify.sdk.android.auth.browser.RedirectUriReceiverActivity. The old manifestPlaceholders in app/build.gradle are no longer supported.
No SDK Download Needed: The plugin automatically resolves, downloads, and configures the spotify-app-remote library AAR file during compilation. You do not need to manually download AAR files or edit your settings.gradle file.
iOS
Register your app in the spotify developer portal. You also need to register your Bundle ID as well as a Redirect URI.
To start using this package first import it in your Dart file.
import'package:spotify_sdk/spotify_sdk.dart';
To connect to the Spotify app you can call connectToSpotifyRemote(...) or getAccessToken(...). In both of these methods you need the client id, which you will find in the Spotify developer dashboard and the redirect url you set there for that specific client.
If you want to use the web api as well you have to use this method to get the access token.
You can specify multiple scopes by separating them with a comma "," as shown below. For more information on scopes you can refer to Spotify Authorization Scopes Guide
final accessToken = awaitSpotifySdk.getAccessToken(clientId: "", redirectUrl: "", scope: "app-remote-control,user-modify-playback-state,playlist-read-private");
On Web you can use the token that you get from getAccessToken(...) and then pass it to connectToSpotifyRemote(...). This will avoid having to send user through two Spotify OAuth prompts. You should not persist this token, nor supply a different token, because the refresh token is only set interally by getAccessToken or connectToSpotifyRemote.
On iOS you can store the token that you get from getAccessToken(...) and then pass it to connectToSpotifyRemote(...) during the next session. This will avoid having to switch to the Spotify app for establishing the connection. This library does not handle storing the token. It is up to you to persist it wherever you see fit. Keep in mind that this feature is currently quite buggy in the native iOS SDK and has many side effects like random disconnections. Proceed with caution.
On iOS Spotify starts playing music when attempting connection. This is a default behavior and there is no official way to prevent this with the currently supported authentication flows. You have the option to pass a Spotify URI upon connection or set it to a blank string to play the last played song. There is an undocumented workaround if you don't want music to start playing which is to pass an invalid Spotify URI instead. This is not officially supported by the Spotify SDK or this library and it can fail or stop working at any time!
Have a look in the example for detailed insights on how you can use this package.
Token Swap & Utilities
If your application architecture uses an intermediate backend to exchange Spotify authorization codes and protect your Client Secret, you can retrieve the raw authorization code using getSwapToken(...):
Seeks the current track to the given position in milliseconds
✔
✔
✔
seekToRelativePosition
Adds to the current position of the track the given milliseconds
✔
✔
✔
setPodcastPlaybackSpeed
Set playback speed for Podcast
✔
❌
❌
setRepeatMode
Set the repeat mode
✔
✔
✔
setShuffle
Set the shuffle mode
✔
✔
✔
skipNext
Skips to next track
✔
✔
✔
skipPrevious
Skips to previous track
✔
✔
✔
skipToIndex
Skips to track at specified index in album or playlist
✔
✔
✔
subscribePlayerContext
Subscribes to the current player context
✔
✔
✔
subscribePlayerState
Subscribes to the current player state
✔
✔
✔
toggleRepeat
Cycles through the repeat modes
✔
✔
✔
toggleShuffle
Cycles through the shuffle modes
✔
✔
✔
On Web, an automatic call to play may not work due to media activation policies which send an error: "Authentication Error: Browser prevented autoplay due to lack of interaction". This error is ignored by the SDK so you can still present a button for the user to click to play or resume to start playback. See the Web SDK Troubleshooting guide for more details.