Skip to content

Commit

Permalink
bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandhuA committed Nov 14, 2024
2 parents 5521b4c df651e9 commit 5a04903
Show file tree
Hide file tree
Showing 15 changed files with 299 additions and 146 deletions.
9 changes: 5 additions & 4 deletions lib/bloc/home_screen_cubit/home_screen_cubit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 16,16 @@ class HomeScreenCubit extends Cubit<HomeScreenState> {

Future<void> loadData() async {
emit(HomeScreenLoading());

final List<Song>? lastplayed = await LastPlayedRepo.fetchLastPlayed();
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? cachedHomeScreenData = await prefs.getString('homeScreenData');
final String? cachedHomeScreenData =
await prefs.getString('homeScreenData');

final String? lastUpdated = await prefs.getString('lastUpdated');

final DateTime now = await DateTime.now();
final DateTime today = await DateTime(now.year, now.month, now.day);
final List<Song> lastplayed = await LastPlayedRepo.fetchLastPlayed();

NewHomeScreenModel? newHomeScreenModel;

if (lastUpdated != null) {
Expand All @@ -34,11 35,11 @@ class HomeScreenCubit extends Cubit<HomeScreenState> {
if (lastUpdateDate.isAtSameMomentAs(today) &&
cachedHomeScreenData != null) {
// Load from cache

newHomeScreenModel =
NewHomeScreenModel.fromJson(jsonDecode(cachedHomeScreenData));

log("---------load from cache----------");

return emit(HomeScreenLoaded(
newHomeScreenModel: newHomeScreenModel,
lastPlayedSongList: lastplayed,
Expand Down
2 changes: 1 addition & 1 deletion lib/bloc/home_screen_cubit/home_screen_state.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 9,7 @@ final class HomeScreenLoading extends HomeScreenState {}

final class HomeScreenLoaded extends HomeScreenState {
final NewHomeScreenModel? newHomeScreenModel;
final List<Song> lastPlayedSongList;
final List<Song>? lastPlayedSongList;

HomeScreenLoaded({
required this.newHomeScreenModel,
Expand Down
7 changes: 7 additions & 0 deletions lib/bloc/playlist/play_list_cubit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 16,7 @@ class PlayListCubit extends Cubit<PlayListState> {
}

void addPlaylist(PlaylistModelHive playList) async {
emit(PlayListLoadingState());
await PlaylistRepo.addPlaylist(playList);
featchPlayList();
}
Expand All @@ -26,4 27,10 @@ class PlayListCubit extends Cubit<PlayListState> {
}) async {
await PlaylistRepo.addSongToPlaylist(playlistModel.name, songModel);
}

void deletePlaylist({required PlaylistModelHive playlist}) async {
emit(PlayListLoadingState());
await PlaylistRepo.deletePlaylist(playlist.name);
featchPlayList();
}
}
48 changes: 48 additions & 0 deletions lib/core/helper_funtions.dart
Original file line number Diff line number Diff line change
@@ -1,6 1,8 @@
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:musiq/models/playlist_model_hive/playlist_model.dart';

//get random number for Shuffle
int getRandomSongIndex({required List songList}) {
Expand Down Expand Up @@ -48,3 50,49 @@ class StatusCodeHandler {
}
}
}


Widget playlistCover({required PlaylistModelHive playlist}) {
return Container(
width: 60,
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
),
child: playlist.songList.length >= 4
? GridView.builder(
physics: const NeverScrollableScrollPhysics(),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 2,
mainAxisSpacing: 2,
),
itemCount: 4,
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
image: DecorationImage(
image: CachedNetworkImageProvider(
playlist.songList[index].image?.last.imageUrl ??
errorImage(),
),
fit: BoxFit.cover,
),
),
);
},
)
: ClipRRect(
borderRadius: BorderRadius.circular(5),
child: CachedNetworkImage(
imageUrl: playlist.songList.isNotEmpty
? playlist.songList[0].image?.last.imageUrl ?? errorImage()
: errorImage(),
placeholder: (context, url) => albumImagePlaceholder(),
errorListener: (value) => albumImagePlaceholder(),
fit: BoxFit.cover,
),
),
);
}
11 changes: 6 additions & 5 deletions lib/data/hive_funtions/last_played_repo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 31,22 @@ class LastPlayedRepo {
}

// ------- featch last played song fron hive data base -------
static Future<List<Song>> fetchLastPlayed() async {
List<Song> lastPlayedSongs = [];
static Future<List<Song>?> fetchLastPlayed() async {
List<Song>? lastPlayedSongs;

try {
final box = Hive.box<Song>('lastPlayedBox');
final box = await Hive.box<Song>('lastPlayedBox');

lastPlayedSongs = box.values.toList()
lastPlayedSongs = await box.values.toList()
..sort((a, b) => b.addedAt!.compareTo(a.addedAt!));

log("Fetched ${lastPlayedSongs.length} last played songs.");
return lastPlayedSongs;
} catch (e) {
log("Error fetching last played songs: $e");
}

return lastPlayedSongs;
return null;
}

//---- clear last played section --------
Expand Down
17 changes: 17 additions & 0 deletions lib/data/hive_funtions/playlist_repo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 95,21 @@ class PlaylistRepo {
Fluttertoast.showToast(msg: "Error clearing playlists: $e");
}
}

static Future<void> deletePlaylist(String playlistName) async {
try {
final box = await Hive.openBox<PlaylistModelHive>(playlistBoxName);

if (box.containsKey(playlistName)) {
await box.delete(playlistName);
log("Playlist deleted: $playlistName");
Fluttertoast.showToast(msg: "Playlist deleted: $playlistName");
} else {
Fluttertoast.showToast(msg: "Playlist '$playlistName' not found");
}
} catch (e) {
log("Error deleting playlist: $e");
Fluttertoast.showToast(msg: "Error deleting playlist: $e");
}
}
}
153 changes: 84 additions & 69 deletions lib/presentation/commanWidgets/bottom_sheet.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 6,7 @@ import 'package:musiq/bloc/playlist/play_list_cubit.dart';
import 'package:musiq/core/colors.dart';
import 'package:musiq/core/global_variables.dart';
import 'package:musiq/core/helper_funtions.dart';
import 'package:musiq/models/song_model/song.dart';
import 'package:musiq/presentation/commanWidgets/favorite_icon.dart';
import 'package:musiq/presentation/commanWidgets/snack_bar.dart';

Expand Down Expand Up @@ -67,7 68,7 @@ class SongOptionsBottomSheet extends StatelessWidget {
onTap: () {
_dismissKeyboard(context);
Navigator.pop(context);
_showPlaylistSelectionBottomSheet(context);
showPlaylistSelectionBottomSheet(context: context, song: song);
},
),
],
Expand Down Expand Up @@ -99,76 100,90 @@ class SongOptionsBottomSheet extends StatelessWidget {
}

//---------playlist bottom sheet-------------
void _showPlaylistSelectionBottomSheet(BuildContext context) {
final playListCubit = context.read<PlayListCubit>();
playListCubit.featchPlayList();
final theme = Theme.of(context);

showModalBottomSheet(
context: context,
backgroundColor: theme.brightness == Brightness.dark
? AppColors.black
: AppColors.white,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (context) {
return BlocBuilder<PlayListCubit, PlayListState>(
builder: (context, state) {
if (state is PlayListLoadingState) {
return const Center(child: CircularProgressIndicator());
} else if (state is FeatchPlayListSuccessState) {
final playlists = state.playlistList;

return Column(
mainAxisSize: MainAxisSize.min,
children: [
const Padding(
padding: EdgeInsets.all(16.0),
child: Text(
"Choose Playlist",
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
Divider(color: AppColors.grey),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: playlists.length,
itemBuilder: (context, index) {
final playlist = playlists[index];
return ListTile(
title: Text(playlist.name),
onTap: () {
context.read<PlayListCubit>().addSongToPlayList(
playlistModel: playlist,
songModel: song,
);
Navigator.pop(context);
customSnackbar(
context: context,
message: "${song.name} added to ${playlist.name}",
bgColor: AppColors.white,
textColor: AppColors.black,
);
},
);
},
),
),
],
);
} else {
return const Center(child: Text("No playlists available"));
}
},
);
},
);
}

void _dismissKeyboard(BuildContext context) {
FocusScope.of(context).requestFocus(FocusNode());
}
}

void showPlaylistSelectionBottomSheet({
required BuildContext context,
required Song song,
}) {
final playListCubit = context.read<PlayListCubit>();
playListCubit.featchPlayList();
final theme = Theme.of(context);

showModalBottomSheet(
context: context,
backgroundColor:
theme.brightness == Brightness.dark ? AppColors.black : AppColors.white,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (context) {
return BlocBuilder<PlayListCubit, PlayListState>(
builder: (context, state) {
if (state is PlayListLoadingState) {
return const Center(child: CircularProgressIndicator());
} else if (state is FeatchPlayListSuccessState) {
final playlists = state.playlistList;

return Column(
mainAxisSize: MainAxisSize.min,
children: [
const Padding(
padding: EdgeInsets.all(16.0),
child: Text(
"Choose Playlist",
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
Divider(color: AppColors.grey),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: playlists.length,
itemBuilder: (context, index) {
final playlist = playlists[index];
return ListTile(
leading: playlist.imagePath == null
? playlist.songList.isEmpty
? CircleAvatar(
backgroundColor: AppColors
.colorList[AppGlobals().colorIndex],
radius: 30,
child: Text(playlist.name[0]),
)
: playlistCover(playlist: playlist)
: SizedBox(),
title: Text(playlist.name),
subtitle: Text("${playlist.songList.length}-Songs"),
onTap: () {
context.read<PlayListCubit>().addSongToPlayList(
playlistModel: playlist,
songModel: song,
);
Navigator.pop(context);
customSnackbar(
context: context,
message: "${song.name} added to ${playlist.name}",
bgColor: AppColors.white,
textColor: AppColors.black,
);
},
);
},
),
),
],
);
} else {
return const Center(child: Text("No playlists available"));
}
},
);
},
);
}

3 changes: 1 addition & 2 deletions lib/presentation/layout/layout_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 52,9 @@ class LayOutPageState extends State<LayOutPage> {

@override
void initState() {
super.initState();

context.read<HomeScreenCubit>().loadData();
context.read<FavoriteBloc>().add(FeatchFavoriteSongEvent());
super.initState();
}

Future<void> _refreshData() async {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 27,7 @@ class _LastPlayedListState extends State<LastPlayedList> {
}

featchLastplayed() async {
lastplayed = await LastPlayedRepo.fetchLastPlayed();
lastplayed = await LastPlayedRepo.fetchLastPlayed() ?? [];
setState(() {});
}

Expand Down
Loading

0 comments on commit 5a04903

Please sign in to comment.