Line data Source code
1 : import 'package:flutter/widgets.dart'; 2 : import 'package:provider/provider.dart'; 3 : import 'package:provider/single_child_widget.dart'; 4 : 5 : /// Mixin which allows `MultiRepositoryProvider` to infer the types 6 : /// of multiple [RepositoryProvider]s. 7 : mixin RepositoryProviderSingleChildWidget on SingleChildWidget {} 8 : 9 : /// {@template repository_provider} 10 : /// Takes a [Create] function that is responsible for creating the repository 11 : /// and a `child` which will have access to the repository via 12 : /// `RepositoryProvider.of(context)`. 13 : /// It is used as a dependency injection (DI) widget so that a single instance 14 : /// of a repository can be provided to multiple widgets within a subtree. 15 : /// 16 : /// ```dart 17 : /// RepositoryProvider( 18 : /// create: (context) => RepositoryA(), 19 : /// child: ChildA(), 20 : /// ); 21 : /// ``` 22 : /// 23 : /// Lazily creates the repository unless `lazy` is set to `false`. 24 : /// 25 : /// ```dart 26 : /// RepositoryProvider( 27 : /// lazy: false,` 28 : /// create: (context) => RepositoryA(), 29 : /// child: ChildA(), 30 : /// ); 31 : /// ``` 32 : /// {@endtemplate} 33 : class RepositoryProvider<T> extends Provider<T> 34 : with RepositoryProviderSingleChildWidget { 35 : /// {@macro repository_provider} 36 2 : RepositoryProvider({ 37 : Key? key, 38 : required Create<T> create, 39 : Widget? child, 40 : bool? lazy, 41 2 : }) : super( 42 : key: key, 43 : create: create, 44 2 : dispose: (_, __) {}, 45 : child: child, 46 : lazy: lazy, 47 : ); 48 : 49 : /// Takes a repository and a [child] which will have access to the repository. 50 : /// A new repository should not be created in `RepositoryProvider.value`. 51 : /// Repositories should always be created using the default constructor 52 : /// within the [Create] function. 53 1 : RepositoryProvider.value({ 54 : Key? key, 55 : required T value, 56 : Widget? child, 57 1 : }) : super.value( 58 : key: key, 59 : value: value, 60 : child: child, 61 : ); 62 : 63 : /// Method that allows widgets to access a repository instance as long as 64 : /// their `BuildContext` contains a [RepositoryProvider] instance. 65 2 : static T of<T>(BuildContext context, {bool listen = false}) { 66 : try { 67 2 : return Provider.of<T>(context, listen: listen); 68 1 : } on ProviderNotFoundException catch (e) { 69 2 : if (e.valueType != T) rethrow; 70 1 : throw FlutterError( 71 : ''' 72 : RepositoryProvider.of() called with a context that does not contain a repository of type $T. 73 : No ancestor could be found starting from the context that was passed to RepositoryProvider.of<$T>(). 74 : 75 : This can happen if the context you used comes from a widget above the RepositoryProvider. 76 : 77 : The context used was: $context 78 1 : ''', 79 : ); 80 : } 81 : } 82 : }