forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic-watch-and-filter-in-riverpod.dart
98 lines (83 loc) · 2.54 KB
/
generic-watch-and-filter-in-riverpod.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// 🐦 Twitter https://twitter.com/vandadnp
// 🔵 LinkedIn https://linkedin.com/in/vandadnp
// 🎥 YouTube https://youtube.com/c/vandadnp
// 💙 Free Flutter Course https://linktr.ee/vandadnp
// 📦 11+ Hours Bloc Course https://youtu.be/Mn254cnduOY
// 🔶 7+ Hours MobX Course https://youtu.be/7Od55PBxYkI
// 🦄 8+ Hours RxSwift Coursde https://youtu.be/xBFWMYmm9ro
// 🤝 Want to support my work? https://buymeacoffee.com/vandad
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
@immutable
class Film {
final String id;
final String title;
final String description;
final bool isFavorite;
const Film({
required this.id,
required this.title,
required this.description,
required this.isFavorite,
});
Film copy({required bool isFavorite}) => Film(
id: id,
title: title,
description: description,
isFavorite: isFavorite,
);
@override
String toString() =>
'Film(id: $id, title: $title, description: $description, isFavorite: $isFavorite)';
@override
bool operator ==(covariant Film other) =>
other.id == id && other.isFavorite == isFavorite;
@override
int get hashCode => id.hashCode;
}
const allFilms = [
Film(
id: '1',
title: 'The Shawshank Redemption',
description: 'Description for The Shawshank Redemption',
isFavorite: false),
Film(
id: '2',
title: 'The Godfather',
description: 'Description for The Godfather',
isFavorite: false),
Film(
id: '3',
title: 'The Godfather: Part II',
description: 'Description for The Godfather: Part II',
isFavorite: false),
Film(
id: '4',
title: 'The Dark Knight',
description: 'Description for The Dark Knight',
isFavorite: false),
];
class FilmsNotifier extends StateNotifier<List<Film>> {
FilmsNotifier() : super(allFilms);
}
// all films
final filmsProvider = StateNotifierProvider<FilmsNotifier, Iterable<Film>>(
(ref) => FilmsNotifier(),
);
Provider<Iterable<P>> watchedProviderWithWhereClause<P>(
AlwaysAliveProviderListenable<Iterable<P>> provider,
bool Function(P) f,
) =>
Provider<Iterable<P>>(
(ref) => ref.watch(provider).where(f),
);
// favorite films
final insteadOfThis = Provider<Iterable<Film>>(
(ref) => ref.watch(filmsProvider).where(
(film) => film.isFavorite,
),
);
final youCanDoThis = watchedProviderWithWhereClause<Film>(
filmsProvider,
(film) => film.isFavorite,
);