fix: insert movies at correct location

main
daniel-michel 2023-11-08 14:59:23 +01:00
parent a977ad1f34
commit da366285bb
2 changed files with 25 additions and 2 deletions

View File

@ -35,7 +35,14 @@ class HomePage extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar(title: const Text("Release Schedule")), appBar: AppBar(
title: const Text("Release Schedule"),
actions: [
FilledButton(
onPressed: () => manager.removeMoviesWhere((movie) => true),
child: const Icon(Icons.delete))
],
),
body: MovieManagerList(manager), body: MovieManagerList(manager),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
child: const Icon(Icons.refresh), child: const Icon(Icons.refresh),

View File

@ -73,13 +73,14 @@ class MovieManager extends ChangeNotifier {
MovieData? existing = MovieData? existing =
firstWhereOrNull(movies, (element) => movie.same(element)); firstWhereOrNull(movies, (element) => movie.same(element));
if (existing == null) { if (existing == null) {
movies.add(movie); _insertMovie(movie);
movie.addListener(() { movie.addListener(() {
_moviesModified(withoutAddingOrRemoving: true); _moviesModified(withoutAddingOrRemoving: true);
}); });
added = true; added = true;
actualMovies.add(movie); actualMovies.add(movie);
} else { } else {
existing.updateWithNew(movie);
actualMovies.add(existing); actualMovies.add(existing);
} }
} }
@ -89,6 +90,21 @@ class MovieManager extends ChangeNotifier {
return actualMovies; return actualMovies;
} }
_insertMovie(MovieData movie) {
int min = 0;
int max = movies.length - 1;
while (min - 1 < max) {
int center = ((min + max) / 2).floor();
int diff = movie.releaseDate.compareTo(movies[center].releaseDate);
if (diff < 0) {
max = center - 1;
} else {
min = center + 1;
}
}
movies.insert(min, movie);
}
removeMoviesWhere(bool Function(MovieData movie) test) { removeMoviesWhere(bool Function(MovieData movie) test) {
bool removedMovies = false; bool removedMovies = false;
for (int i = movies.length - 1; i >= 0; i--) { for (int i = movies.length - 1; i >= 0; i--) {