From 29ffc280a59eddf6488044fff6e2cedfee2192fc Mon Sep 17 00:00:00 2001 From: Kingkor Roy Tirtho Date: Fri, 15 Mar 2024 22:06:40 +0600 Subject: [PATCH] feat: add search provider --- lib/provider/spotify/search/search.dart | 92 +++++++++++++++++++++++++ lib/provider/spotify/spotify.dart | 2 + 2 files changed, 94 insertions(+) create mode 100644 lib/provider/spotify/search/search.dart diff --git a/lib/provider/spotify/search/search.dart b/lib/provider/spotify/search/search.dart new file mode 100644 index 00000000..70b837dc --- /dev/null +++ b/lib/provider/spotify/search/search.dart @@ -0,0 +1,92 @@ +part of '../spotify.dart'; + +class SearchState extends PaginatedState { + final String query; + SearchState({ + required super.items, + required super.offset, + required super.limit, + required super.hasMore, + required this.query, + }); + + @override + SearchState copyWith({ + List? items, + int? offset, + int? limit, + bool? hasMore, + String? query, + }) { + return SearchState( + items: items ?? this.items, + offset: offset ?? this.offset, + limit: limit ?? this.limit, + hasMore: hasMore ?? this.hasMore, + query: query ?? this.query, + ); + } +} + +class SearchNotifier + extends FamilyPaginatedAsyncNotifier, SearchType> { + SearchNotifier() : super(); + + @override + fetch(arg, offset, limit) async { + if (state.value == null) return []; + final results = await spotify.search + .get( + state.value!.query, + types: [arg], + market: ref.read(userPreferencesProvider).recommendationMarket, + ) + .getPage(limit, offset); + + return results.expand((e) => e.items ?? []).toList().cast(); + } + + @override + build(arg) async { + ref.watch(spotifyProvider); + ref.watch( + userPreferencesProvider.select((value) => value.recommendationMarket), + ); + + final results = await fetch(arg, 0, 10); + + return SearchState( + items: results, + offset: 0, + limit: 10, + hasMore: results.length == 10, + query: "", + ); + } + + Future search(String query) async { + if (state.value == null) return; + + state = AsyncData( + state.value!.copyWith( + query: query, + ), + ); + + await update((state) async { + final results = await fetch(arg, 0, 10); + + return state.copyWith( + items: results, + offset: 0, + limit: 10, + hasMore: results.length == 10, + ); + }); + } +} + +final searchProvider = + AsyncNotifierProvider.family( + () => SearchNotifier(), +); diff --git a/lib/provider/spotify/spotify.dart b/lib/provider/spotify/spotify.dart index 4d3921a5..40f7a940 100644 --- a/lib/provider/spotify/spotify.dart +++ b/lib/provider/spotify/spotify.dart @@ -43,6 +43,8 @@ part 'playlist/tracks.dart'; part 'playlist/featured.dart'; part 'playlist/generate.dart'; +part 'search/search.dart'; + part 'user/me.dart'; part 'utils/mixin.dart';