Line data Source code
1 : part of flutter_data; 2 : 3 : /// A [Relationship] that models a to-many ownership. 4 : /// 5 : /// Example: An author who has many books 6 : /// ``` 7 : /// class Author with DataModel<Author> { 8 : /// @override 9 : /// final int id; 10 : /// final String name; 11 : /// final HasMany<Book> books; 12 : /// 13 : /// Todo({this.id, this.name, this.books}); 14 : /// } 15 : ///``` 16 : class HasMany<E extends DataModel<E>> extends Relationship<E, Set<E>> { 17 : /// Creates a [HasMany] relationship, with an optional initial [Set<E>]. 18 : /// 19 : /// Example: 20 : /// ``` 21 : /// final book = Book(title: 'Harry Potter'); 22 : /// final author = Author(id: 1, name: 'JK Rowling', books: HasMany({book})); 23 : /// ``` 24 : /// 25 : /// See also: [IterableRelationshipExtension<E>.asHasMany] 26 2 : HasMany([Set<E>? models]) : super(models); 27 : 28 1 : HasMany._(Iterable<String> keys, bool _wasOmitted) 29 1 : : super._(keys, _wasOmitted); 30 : 31 2 : HasMany.remove() : super._remove(); 32 : 33 : /// For internal use with `json_serializable`. 34 1 : factory HasMany.fromJson(final Map<String, dynamic> map) { 35 2 : if (map['_'][0] == null) { 36 2 : final wasOmitted = map['_'][1] as bool; 37 1 : return HasMany._({}, wasOmitted); 38 : } 39 2 : final keys = <String>{...map['_'][0]}; 40 1 : return HasMany._(keys, false); 41 : } 42 : 43 : /// Returns a [StateNotifier] which emits the latest [Set<E>] representing 44 : /// this [HasMany] relationship. 45 1 : @override 46 : DelayedStateNotifier<Set<E>> watch() { 47 7 : return _graphEvents.where((e) => e.isNotEmpty).map((e) => toSet()); 48 : } 49 : 50 1 : @override 51 2 : String toString() => 'HasMany<$E>($_prop)'; 52 : } 53 : 54 : extension IterableRelationshipExtension<T extends DataModel<T>> on Set<T> { 55 : /// Converts a [Set<T>] into a [HasMany<T>]. 56 : /// 57 : /// Equivalent to using the constructor as `HasMany(set)`. 58 2 : HasMany<T> get asHasMany => HasMany<T>(this); 59 : }