feat: add riverpod based favorite album provider

This commit is contained in:
Kingkor Roy Tirtho 2024-03-13 17:35:33 +06:00
parent 35e9920b51
commit 39d07567c4
5 changed files with 115 additions and 0 deletions

View File

@ -0,0 +1,61 @@
part of '../spotify.dart';
class FavoriteAlbumState extends PaginatedState<AlbumSimple> {
FavoriteAlbumState({
required super.items,
required super.offset,
required super.limit,
});
@override
FavoriteAlbumState copyWith({
items,
offset,
limit,
}) {
return FavoriteAlbumState(
items: items ?? this.items,
offset: offset ?? this.offset,
limit: limit ?? this.limit,
);
}
}
class FavoriteAlbumNotifier
extends PaginatedAsyncNotifier<AlbumSimple, FavoriteAlbumState>
with SpotifyMixin<FavoriteAlbumState> {
@override
Future<List<AlbumSimple>> fetch(int offset, int limit) {
return spotify.me
.savedAlbums()
.getPage(limit, offset)
.then((value) => value.items?.toList() ?? []);
}
@override
build() async {
ref.watch(spotifyProvider);
return FavoriteAlbumState(
items: await fetch(0, 20),
offset: 0,
limit: 20,
);
}
Future<void> saveAlbums(List<String> ids) async {
if (state.value == null) return;
await spotify.me.saveAlbums(ids);
state = await AsyncValue.guard(() async {
final albums = await spotify.albums.list(ids);
return state.value!.copyWith(
items: [
...state.value!.items,
...albums,
],
);
});
}
}

View File

@ -0,0 +1,10 @@
library spotify;
import 'package:spotify/spotify.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:spotube/provider/spotify_provider.dart';
part 'album/favorite.dart';
part 'utils/mixin.dart';
part 'utils/state.dart';
part 'utils/provider.dart';

View File

@ -0,0 +1,5 @@
part of '../spotify.dart';
mixin SpotifyMixin<T> on AsyncNotifier<T> {
SpotifyApi get spotify => ref.read(spotifyProvider);
}

View File

@ -0,0 +1,23 @@
part of '../spotify.dart';
abstract class PaginatedAsyncNotifier<K, T extends PaginatedState<K>>
extends AsyncNotifier<T> {
Future<List<K>> fetch(int offset, int limit);
Future<void> fetchMore() async {
if (state.value == null || !state.value!.hasMore) return;
await update(
(state) async {
final items = await fetch(state.offset + state.limit, state.limit);
return state.copyWith(
items: [
...state.items,
...items,
],
offset: state.offset + state.limit,
) as T;
},
);
}
}

View File

@ -0,0 +1,16 @@
part of '../spotify.dart';
abstract class PaginatedState<K> {
final List<K> items;
final int offset;
final int limit;
final bool hasMore;
PaginatedState({
required this.items,
required this.offset,
required this.limit,
}) : hasMore = items.length >= limit;
PaginatedState<K> copyWith({List<K>? items, int? offset, int? limit});
}