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