refreshAccessToken method

Future<void> refreshAccessToken()

Refreshes the access token using the stored refresh token.

Implementation

Future<void> refreshAccessToken() async {
  final prefs = await SharedPreferences.getInstance();
  final refreshToken = prefs.getString('refresh_token');
  final clientId = prefs.getString('client_id');

  if (refreshToken == null) {
    throw Exception("Refresh token not found. Please re-authenticate.");
  }

  if (clientId == null) {
    throw Exception("Client ID not found. Please re-authenticate.");
  }

  final response = await http.post(
    Uri.parse('https://accounts.spotify.com/api/token'),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: {
      'client_id': clientId,
      'grant_type': 'refresh_token',
      'refresh_token': refreshToken,
    },
  );

  if (response.statusCode != 200) {
    throw Exception("Could not refresh token: ${response.body}");
  }

  final jsonBody = jsonDecode(response.body);
  jsonBody['client_id'] = clientId;
  await _saveTokenData(jsonBody, refreshTokenOverride: refreshToken);
  _accessToken = jsonBody['access_token'];
}