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 : /// For internal use with `json_serializable`. 32 1 : factory HasMany.fromJson(final Map<String, dynamic> map) { 33 2 : if (map['_'][0] == null) { 34 2 : final wasOmitted = map['_'][1] as bool; 35 1 : return HasMany._({}, wasOmitted); 36 : } 37 3 : final keys = <String>{...map['_'][0]}; 38 1 : return HasMany._(keys, false); 39 : } 40 : 41 : /// Returns a [StateNotifier] which emits the latest [Set<E>] representing 42 : /// this [HasMany] relationship. 43 1 : @override 44 : StateNotifier<Set<E>> watch() { 45 6 : return _graphEvents.where((e) => e.isNotEmpty).map((e) => this); 46 : } 47 : 48 0 : @override 49 0 : String toString() => 'HasMany<$E>(${toSet()})'; 50 : } 51 : 52 : extension IterableRelationshipExtension<T extends DataModel<T>> on Set<T> { 53 : /// Converts a [Set<T>] into a [HasMany<T>]. 54 : /// 55 : /// Equivalent to using the constructor as `HasMany(set)`. 56 2 : HasMany<T> get asHasMany => HasMany<T>(this); 57 : }