mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-01-24 21:57:58 +00:00
Compare commits
2 Commits
cherrypick
...
0.0.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1aa0ae045e | ||
|
|
12d877333a |
38
.github/workflows/pipeline.yml
vendored
38
.github/workflows/pipeline.yml
vendored
@@ -1,38 +0,0 @@
|
||||
name: Melos + FVM CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: dart-lang/setup-dart@v1
|
||||
# также актуализация Flutter, если нужен fvm
|
||||
|
||||
- name: Install FVM
|
||||
run: dart pub global activate fvm
|
||||
|
||||
- name: Install Flutter version via FVM
|
||||
run: fvm install
|
||||
|
||||
# ВАЖНО: активируем melos через flutter, чтобы не было несовместимости
|
||||
- name: Install Melos
|
||||
run: fvm flutter pub global activate melos
|
||||
|
||||
- name: Bootstrap workspace
|
||||
run: fvm flutter pub global run melos bootstrap
|
||||
|
||||
- name: CodeGen
|
||||
run: fvm flutter pub global run melos run codegen
|
||||
|
||||
- name: Analyze all packages
|
||||
run: fvm flutter pub global run melos run analyze
|
||||
|
||||
- name: Run all tests
|
||||
run: fvm flutter pub global run melos run test
|
||||
33
.gitignore
vendored
33
.gitignore
vendored
@@ -1,20 +1,21 @@
|
||||
.DS_Store
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
# See https://www.dartlang.org/guides/libraries/private-files
|
||||
|
||||
# Files and directories created by pub
|
||||
.dart_tool/
|
||||
.idea/
|
||||
.vscode/
|
||||
.packages
|
||||
build/
|
||||
# If you're building an application, you may want to check-in your pubspec.lock
|
||||
pubspec.lock
|
||||
|
||||
# Directory created by dartdoc
|
||||
# If you don't generate documentation locally you can remove this line.
|
||||
doc/api/
|
||||
|
||||
**/*.g.dart
|
||||
**/*.gr.dart
|
||||
**/*.freezed.dart
|
||||
**/*.cherrypick_injectable.g.dart
|
||||
|
||||
pubspec_overrides.yaml
|
||||
|
||||
melos_cherrypick.iml
|
||||
melos_cherrypick_workspace.iml
|
||||
melos_cherrypick_flutter.iml
|
||||
# Avoid committing generated Javascript files:
|
||||
*.dart.js
|
||||
*.info.json # Produced by the --dump-info flag.
|
||||
*.js # When generated by dart2js. Don't specify *.js if your
|
||||
# project includes source files written in JavaScript.
|
||||
*.js_
|
||||
*.js.deps
|
||||
*.js.map
|
||||
|
||||
293
CHANGELOG.md
293
CHANGELOG.md
@@ -1,293 +0,0 @@
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## 2025-05-28
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.4`](#cherrypick_generator---v110-dev4)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.4`
|
||||
|
||||
- **FIX**: fixed warnings.
|
||||
|
||||
|
||||
## 2025-05-23
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v1.1.0-dev.1`](#cherrypick_annotations---v110-dev1)
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.3`](#cherrypick_generator---v110-dev3)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.0-dev.1`
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.3`
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
|
||||
## 2025-05-23
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.2`](#cherrypick_generator---v110-dev2)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.2`
|
||||
|
||||
- **FIX**: update instance generator code.
|
||||
|
||||
|
||||
## 2025-05-22
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.2.0-dev.1`](#cherrypick---v220-dev1)
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.1`](#cherrypick_generator---v110-dev1)
|
||||
- [`cherrypick_flutter` - `v1.1.2-dev.1`](#cherrypick_flutter---v112-dev1)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.2-dev.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v2.2.0-dev.1`
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.1`
|
||||
|
||||
- **FIX**: optimize code.
|
||||
|
||||
|
||||
## 2025-05-22
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.2.0-dev.0`](#cherrypick---v220-dev0)
|
||||
- [`cherrypick_annotations` - `v1.1.0-dev.0`](#cherrypick_annotations---v110-dev0)
|
||||
- [`cherrypick_flutter` - `v1.1.2-dev.0`](#cherrypick_flutter---v112-dev0)
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.0`](#cherrypick_generator---v110-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v2.2.0-dev.0`
|
||||
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
- **FEAT**: implement toInstanceAync binding.
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.0-dev.0`
|
||||
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.2-dev.0`
|
||||
|
||||
- **FIX**: fix warning.
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.0`
|
||||
|
||||
- **FIX**: fix warning conflict with names.
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: fix module generator.
|
||||
- **FIX**: fix generator for singletone annotation.
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement async mode for instance/provide annotations.
|
||||
- **FEAT**: generate instance async code.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement named dependency.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
|
||||
## 2025-05-19
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v1.1.1`](#cherrypick_flutter---v111)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.1.0`](#cherrypick---v210)
|
||||
|
||||
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
|
||||
|
||||
- `cherrypick` - `v2.1.0`
|
||||
- `cherrypick_flutter` - `v1.1.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.1`
|
||||
|
||||
#### `cherrypick` - `v2.1.0`
|
||||
|
||||
|
||||
## 2025-05-16
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.1.0-dev.1`](#cherrypick---v210-dev1)
|
||||
- [`cherrypick_flutter` - `v1.1.1-dev.1`](#cherrypick_flutter---v111-dev1)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v2.1.0-dev.1`
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: support passing params when resolving dependency recursively in parent scope.
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.1-dev.1`
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
|
||||
## 2025-05-16
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.0.2`](#cherrypick---v202)
|
||||
- [`cherrypick_flutter` - `v1.1.1`](#cherrypick_flutter---v111)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v2.0.2`
|
||||
|
||||
- **FIX**: support passing params when resolving dependency recursively in parent scope.
|
||||
|
||||
|
||||
## 2025-05-03
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v1.1.0`](#cherrypick_flutter---v110)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.0`
|
||||
|
||||
- **FIX**: update description.
|
||||
- **FIX**: update gitignore.
|
||||
- **FEAT**: modify api in CherryPickProvider.
|
||||
|
||||
|
||||
## 2025-05-02
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.0.1`](#cherrypick---v201)
|
||||
- [`cherrypick_flutter` - `v1.0.1`](#cherrypick_flutter---v101)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.0.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v2.0.1`
|
||||
|
||||
- **FIX**: fix warning.
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# Contributors
|
||||
|
||||
- Sergey Penkovsky <sergey.penkovsky@gmail.com>
|
||||
- Klim Yaroshevich <yarashevich_kv@st.by>
|
||||
328
README.md
328
README.md
@@ -1,145 +1,247 @@
|
||||
# CherryPick Workspace
|
||||
# dart_di
|
||||
|
||||
CherryPick Workspace is a modular, open-source dependency injection ecosystem for Dart and Flutter, designed to offer lightweight, flexible, and scalable DI suitable for both backend and frontend (Flutter) development. This monorepo contains the main DI runtime library, annotation helpers, code generation for modular bindings, and seamless Flutter integration.
|
||||
Экспериментальная разработка DI на ЯП Dart
|
||||
|
||||
---
|
||||
## Документация
|
||||
|
||||
## Packages Overview
|
||||
### Быстрый старт
|
||||
|
||||
- **[`cherrypick`](./cherrypick)**
|
||||
The core dependency injection library. Supports modular bindings, hierarchical scopes, named and singleton bindings, provider functions (sync/async), runtime parameters, and test-friendly composition.
|
||||
_Intended for use in pure Dart and Flutter projects._
|
||||
Основным классом для всех операций является `DiContainer`. Вы можете зарегистрировать свои зависимости,
|
||||
получив `ResolvingContext` через метод `bind<T>()` и используя его различные методы разрешений.
|
||||
Далее вы можете получить зависимости с помощью `resolve<T>()`.
|
||||
|
||||
- **[`cherrypick_annotations`](./cherrypick_annotations)**
|
||||
A set of Dart annotations (`@module`, `@singleton`, `@instance`, `@provide`, `@named`, `@params`) enabling concise, declarative DI modules and providers, primarily for use with code generation tools.
|
||||
|
||||
- **[`cherrypick_generator`](./cherrypick_generator)**
|
||||
A [source_gen](https://pub.dev/packages/source_gen)-based code generator that automatically converts your annotated modules and providers into ready-to-use boilerplate for registration and resolution within your app.
|
||||
_Reduces manual wiring and errors; compatible with build_runner._
|
||||
|
||||
- **[`cherrypick_flutter`](./cherrypick_flutter)**
|
||||
Adds Flutter-native integration, exposing DI scopes and modules to the widget tree through `CherryPickProvider` and enabling dependency management throughout your Flutter app.
|
||||
|
||||
---
|
||||
|
||||
## Why CherryPick?
|
||||
|
||||
- **Zero-overhead and intuitive API:**
|
||||
Clean, minimal syntax, strong typing, powerful binding lifecycle control.
|
||||
- **High testability:**
|
||||
Supports overriding and hierarchical scope trees.
|
||||
- **Both Sync & Async support:**
|
||||
Register and resolve async providers, factories, and dependencies.
|
||||
- **Seamless code generation:**
|
||||
Effortless setup with annotations + generator—skip boilerplate!
|
||||
- **Works with or without Flutter.**
|
||||
- **Production ready:**
|
||||
Robust enough for apps, packages, and server-side Dart.
|
||||
- **Extensible & Modular:**
|
||||
Add bindings at runtime, use sub-modules, or integrate via codegen.
|
||||
|
||||
---
|
||||
|
||||
## Get Started
|
||||
|
||||
### 1. Add dependencies
|
||||
|
||||
In your `pubspec.yaml`:
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick: ^<latest-version>
|
||||
cherrypick_annotations: ^<latest-version>
|
||||
|
||||
dev_dependencies:
|
||||
build_runner: ^<latest>
|
||||
cherrypick_generator: ^<latest-version>
|
||||
```
|
||||
|
||||
For Flutter projects, add:
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick_flutter: ^<latest-version>
|
||||
```
|
||||
|
||||
### 2. Write a DI Module (with annotations)
|
||||
Пример:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
final container = DiContainer();
|
||||
container.bind<SomeService>().toValue(SomeServiceImpl());
|
||||
/*
|
||||
...
|
||||
*/
|
||||
|
||||
@module()
|
||||
abstract class MyModule extends Module {
|
||||
@singleton()
|
||||
ApiClient apiClient() => ApiClient();
|
||||
// Метод `resolve` просто возвращает зарегистрированный ранее экземпляр
|
||||
final someService = container.resolve<SomeService>();
|
||||
```
|
||||
|
||||
@provide()
|
||||
DataRepository dataRepo(ApiClient client) => DataRepository(client);
|
||||
### Ленивая инициализация
|
||||
|
||||
@provide()
|
||||
String greeting(@params() String name) => 'Hello, $name!';
|
||||
Если вам нужно создать объект в момент резолвинга, вы можете использовать ленивую (другими словами, по запросу) инициализацию объекта
|
||||
с помощью метода `toFactoryN()`.
|
||||
|
||||
Пример:
|
||||
|
||||
```dart
|
||||
final container = DiContainer();
|
||||
// В методе `toFactory` вы просто определяете, как построить экземпляр через фабричную лямбду
|
||||
container.bind<SomeService>().toFactory( () => SomeServiceImpl() );
|
||||
/*
|
||||
...
|
||||
*/
|
||||
// Метод `resolve()` будет создавать экземпляр через зарегистрированную фабричную лямбду каждый раз, когда вы вызываете его
|
||||
final someService = container.resolve<SomeService>();
|
||||
final anotherSomeService = container.resolve<SomeService>();
|
||||
assert(someService != anotherSomeService);
|
||||
```
|
||||
|
||||
Но обычно у вас есть много типов с разными зависимостями, которые образуют граф зависимостей.
|
||||
|
||||
Пример:
|
||||
|
||||
```dart
|
||||
class A {}
|
||||
class B {}
|
||||
|
||||
class C {
|
||||
final A a;
|
||||
final B b;
|
||||
|
||||
C(this.a, this.b);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Generate the bindings
|
||||
|
||||
```sh
|
||||
dart run build_runner build
|
||||
# or for Flutter:
|
||||
flutter pub run build_runner build
|
||||
```
|
||||
Если вам нужно зарегистрировать некоторый тип, зависящий от других типов из контейнера,
|
||||
вы можете использовать методы `toFactory1<T1>` - `toFactory8<T1 ... T8>`, где число в конце,
|
||||
является количеством запрошенных через аргументы типов зависимостей.
|
||||
(Обратите внимание, что вам нужно определить все зависимости в аргументах - `toFactory2<A1, A2>`).
|
||||
|
||||
The generator will create a `$MyModule` class with binding code.
|
||||
|
||||
### 4. Install and Resolve
|
||||
Пример:
|
||||
|
||||
```dart
|
||||
final scope = CherryPick.openRootScope()
|
||||
..installModules([$MyModule()]);
|
||||
class SomeService {
|
||||
final A a;
|
||||
final B b;
|
||||
|
||||
final repo = scope.resolve<DataRepository>();
|
||||
final greeting = scope.resolveWithParams<String>('John'); // 'Hello, John!'
|
||||
```
|
||||
|
||||
_For Flutter, wrap your app with `CherryPickProvider` for DI scopes in the widget tree:_
|
||||
|
||||
```dart
|
||||
void main() {
|
||||
runApp(
|
||||
CherryPickProvider(child: MyApp()),
|
||||
);
|
||||
SomeService(this.a, this.b);
|
||||
}
|
||||
|
||||
final container = DiContainer();
|
||||
container.bind<A>(A::class).toFactory (() => A());
|
||||
container.bind<B>(B::class).toFactory (() => B());
|
||||
|
||||
/// В фабричной лямбде вы определяете, как построить зависимость от других зависимостей
|
||||
/// (Порядок разрешенных экземпляров соответствует порядку типов аргументов)
|
||||
container.bind<SomeService>().toFactory2<A, B>((a, b) => SomeService(a, b));
|
||||
|
||||
/*
|
||||
...
|
||||
*/
|
||||
|
||||
/// Получаем экземпляр `SomeService` через resolve своих зависимостей.
|
||||
/// В нашем случае - это resolve A и B
|
||||
/// Внимание!!! То, что он будет создавать новые экземпляры A и B каждый раз, когда вы вызываете `resolve` SomeService
|
||||
final someService = container.resolve<SomeService>();
|
||||
```
|
||||
|
||||
---
|
||||
### Время жизни экземпляров и контроль области видимости
|
||||
|
||||
## Features at a Glance
|
||||
Если вы хотите создать экземпляр зарегистрированной зависимости только один раз,
|
||||
и вам нужно получить/разрешить зависимость много раз в контейнере, то вы можете зарегистрировать
|
||||
свою зависимость с добавлением `asSingeton()`. Например:
|
||||
|
||||
- ⚡ **Fast, lightweight DI** for any Dart/Flutter project
|
||||
- 🧩 **Modular & hierarchical scopes** (root, subscopes)
|
||||
- 🔖 **Named/bound/singleton instances** out of the box
|
||||
- 🔄 **Sync and async provider support**
|
||||
- ✏️ **Runtime parameters for dynamic factory methods**
|
||||
- 🏷️ **Code generator** for annotation-based DI setup (`cherrypick_generator`)
|
||||
- 🕹️ **Deep Flutter integration** via `CherryPickProvider`
|
||||
```dart
|
||||
final container = DiContainer();
|
||||
container.bind<A>()
|
||||
.toFactory(() => A())
|
||||
.asSingleton();
|
||||
|
||||
---
|
||||
container
|
||||
.bind<B>()
|
||||
.toFactory(() => B());
|
||||
.asSingleton();
|
||||
|
||||
## Example Usage
|
||||
container.bind<SomeService>().toFactory2<A, B>((a, b) -> SomeService(a, b));
|
||||
|
||||
Please see:
|
||||
- [`cherrypick/README.md`](./cherrypick/README.md) for core DI features and examples
|
||||
- [`cherrypick_flutter/README.md`](./cherrypick_flutter/README.md) for Flutter-specific usage
|
||||
- [`cherrypick_annotations/README.md`](./cherrypick_annotations/README.md) and [`cherrypick_generator/README.md`](./cherrypick_generator/README.md) for codegen and annotations
|
||||
// Код выше означает: Контейнер, регистрирует создание A и B только в первый раз, когда оно будет запрошен,
|
||||
// и регистрирует создание SomeService каждый раз, когда оно будет запрошен.
|
||||
|
||||
---
|
||||
final a = container.resolve<A>();
|
||||
final b = container.resolve<B>();
|
||||
final anotherA = container.resolve<A>();
|
||||
final anotherB = container.resolve<B>();
|
||||
|
||||
## Contribution & License
|
||||
assert(a == anotherA && b == anotherB);
|
||||
|
||||
- **Contributions:** PRs, issues, and feedback are welcome on [GitHub](https://github.com/pese-git/cherrypick).
|
||||
- **License:** Apache 2.0 for all packages in this workspace.
|
||||
final someService = container.resolve<SomeService>();
|
||||
final anotherSomeService = container.resolve<SomeService>();
|
||||
|
||||
---
|
||||
assert(someService != anotherSomeService);
|
||||
```
|
||||
|
||||
**Happy Cherry Picking! 🍒**
|
||||
Если вы хотите сразу создать свой зарегистрированный экземпляр, вы можете вызвать `resolve()`. Например:
|
||||
|
||||
|
||||
```dart
|
||||
final container = DiContainer();
|
||||
// Это заставит создать зависимость после регистрации
|
||||
container.bind <SomeService>()
|
||||
.toFactory(() => SomeService())
|
||||
.asSingleton()
|
||||
.resolve();
|
||||
```
|
||||
|
||||
Когда вы работаете со сложным приложением, в большинстве случаев вы можете работать со многими модулями с собственными зависимостями.
|
||||
Эти модули могут быть настроены различными `DiContainer`-ми. И вы можете прикрепить контейнер к другому, как родительский.
|
||||
В этом случае родительские зависимости будут видны для дочернего контейнера,
|
||||
и через него вы можете формировать различные области видимости зависимостей. Например:
|
||||
|
||||
```dart
|
||||
final parentContainer = DiContainer();
|
||||
parentContainer.bind<A>().toFactory(() => A())
|
||||
|
||||
final childContainer = DiContainer(parentContainer);
|
||||
// Обратите внимание, что родительская зависимость A видна для дочернего контейнера
|
||||
final a = childContainer.resolve<A>();
|
||||
|
||||
/*
|
||||
// Но следующий код потерпит неудачу с ошибкой, потому что родитель не знает о своем потомке.
|
||||
final parentContainer = DiContainer();
|
||||
final childContainer = DiContainer();
|
||||
childContainer.bind<A>().toFactory(() => A());
|
||||
|
||||
// Выдает ошибку
|
||||
final a = parentContainer.resolve<A>();
|
||||
*/
|
||||
```
|
||||
|
||||
### Структура библиотеки
|
||||
|
||||
Библиотека состоит из DiContainer и Resolver.
|
||||
DiContainer - это контейнер со всеми Resolver для разных типов. А `Resolver` - это просто объект, который знает, как разрешить данный тип.
|
||||
Многие из resolver-ов обернуты другими, поэтому они могут быть составлены для разных вариантов использования.
|
||||
Resolver - интерфейс, поэтому он имеет много реализаций. Основным является ResolvingContext.
|
||||
Вы можете думать об этом как об объекте контекста, который имеет вспомогательные методы для создания различных вариантов resolver-ов (`toFactory`,` toValue`, `asSingleton`).
|
||||
Но все они просто используют метод `toResolver` для определения некоторого корневого resolver в контексте.
|
||||
Когда вы запрашиваете тип из контейнера с помощью метода `resolve<T>()`, он просто находит контекст для типа и вызывает корневой resolver, который может вызывать другие resolver-ы.
|
||||
|
||||
|
||||
Пример (из ```example```):
|
||||
|
||||
```dart
|
||||
import 'dart:async';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:dart_di/dart_di.dart';
|
||||
|
||||
void main() async {
|
||||
final dataModule = new DiContainer()
|
||||
..bind<ApiClient>().toValue(new ApiClientMock())
|
||||
..bind<DataRepository>()
|
||||
.toFactory1<ApiClient>((c) => new NetworkDataRepository(c))
|
||||
..bind<DataBloc>().toFactory1<DataRepository>((s) => new DataBloc(s));
|
||||
|
||||
final dataBloc = dataModule.resolve<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
|
||||
await dataBloc.fetchData();
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
Stream<String> get data => _dataController.stream;
|
||||
StreamController<String> _dataController = new StreamController.broadcast();
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
Future<void> fetchData() async {
|
||||
try {
|
||||
_dataController.sink.add(await _dataRepository.getData());
|
||||
} catch (e) {
|
||||
_dataController.sink.addError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_dataController.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class DataRepository {
|
||||
Future<String> getData();
|
||||
}
|
||||
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async => await _apiClient.sendRequest(
|
||||
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String url, String token, Map requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String url, String token, Map requestBody}) async {
|
||||
return 'hello world';
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"flutter": "3.24.2",
|
||||
"flavors": {}
|
||||
}
|
||||
24
cherrypick/.gitignore
vendored
24
cherrypick/.gitignore
vendored
@@ -1,24 +0,0 @@
|
||||
# See https://www.dartlang.org/guides/libraries/private-files
|
||||
|
||||
# Files and directories created by pub
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
||||
# If you're building an application, you may want to check-in your pubspec.lock
|
||||
pubspec.lock
|
||||
|
||||
# Directory created by dartdoc
|
||||
# If you don't generate documentation locally you can remove this line.
|
||||
doc/api/
|
||||
|
||||
# Avoid committing generated Javascript files:
|
||||
*.dart.js
|
||||
*.info.json # Produced by the --dump-info flag.
|
||||
*.js # When generated by dart2js. Don't specify *.js if your
|
||||
# project includes source files written in JavaScript.
|
||||
*.js_
|
||||
*.js.deps
|
||||
*.js.map
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
@@ -1 +0,0 @@
|
||||
Sergey Penkovsky <sergey.penkovsky@gmail.com>
|
||||
@@ -1,69 +0,0 @@
|
||||
## 2.2.0-dev.1
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
## 2.2.0-dev.0
|
||||
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
- **FEAT**: implement toInstanceAync binding.
|
||||
|
||||
## 2.1.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 2.1.0-dev.1
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: support passing params when resolving dependency recursively in parent scope.
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
|
||||
## 2.0.2
|
||||
- **FIX**: support passing params when resolving dependency recursively in parent scope.
|
||||
|
||||
## 2.1.0-dev.0
|
||||
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
|
||||
## 2.0.1
|
||||
- **FIX**: fix warning.
|
||||
|
||||
## 2.0.0
|
||||
- **FEAT**: support for Dart 3.0.
|
||||
|
||||
## 1.1.0
|
||||
- **FEAT**: verified Dart 3.0 support.
|
||||
|
||||
## 1.0.4
|
||||
- **FIX**: Fixed exception "ConcurrentModificationError".
|
||||
|
||||
## 1.0.3
|
||||
- **FEAT**: Added provider with params.
|
||||
|
||||
## 1.0.2
|
||||
- **DOCS**: Updated docs and fixed syntax error.
|
||||
|
||||
## 1.0.1
|
||||
- **FIX**: Fixed syntax error.
|
||||
|
||||
## 1.0.0
|
||||
- **REFACTOR**: Refactored code and added experimental API.
|
||||
|
||||
## 0.1.2+1
|
||||
- **FIX**: Fixed initialization error.
|
||||
|
||||
## 0.1.2
|
||||
- **FIX**: Fixed warnings in code.
|
||||
|
||||
## 0.1.1+2
|
||||
- **MAINT**: Updated libraries and fixed warnings.
|
||||
|
||||
## 0.1.1+1
|
||||
- **MAINT**: Updated pubspec and readme.md.
|
||||
|
||||
## 0.1.1
|
||||
- **MAINT**: Updated pubspec.
|
||||
|
||||
## 0.1.0
|
||||
- **INIT**: Initial release.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,255 +0,0 @@
|
||||
# CherryPick
|
||||
|
||||
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter. It provides an easy-to-use system for registering, scoping, and resolving dependencies using modular bindings and hierarchical scopes. The design enables cleaner architecture, testability, and modular code in your applications.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### Binding
|
||||
|
||||
A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
|
||||
|
||||
|
||||
- Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
|
||||
- Lazy providers (sync/async functions)
|
||||
- Provider functions supporting dynamic parameters
|
||||
- Named instances for resolving by string key
|
||||
- Optional singleton lifecycle
|
||||
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
// Provide a direct instance
|
||||
Binding<String>().toInstance("Hello world");
|
||||
|
||||
// Provide an async direct instance
|
||||
Binding<String>().toInstanceAsync(Future.value("Hello world"));
|
||||
|
||||
// Provide a lazy sync instance using a factory
|
||||
Binding<String>().toProvide(() => "Hello world");
|
||||
|
||||
// Provide a lazy async instance using a factory
|
||||
Binding<String>().toProvideAsync(() async => "Hello async world");
|
||||
|
||||
// Provide an instance with dynamic parameters (sync)
|
||||
Binding<String>().toProvideWithParams((params) => "Hello $params");
|
||||
|
||||
// Provide an instance with dynamic parameters (async)
|
||||
Binding<String>().toProvideAsyncWithParams((params) async => "Hello $params");
|
||||
|
||||
// Named instance for retrieval by name
|
||||
Binding<String>().toProvide(() => "Hello world").withName("my_string");
|
||||
|
||||
// Mark as singleton (only one instance within the scope)
|
||||
Binding<String>().toProvide(() => "Hello world").singleton();
|
||||
```
|
||||
|
||||
### Module
|
||||
|
||||
A **Module** is a logical collection point for bindings, designed for grouping and initializing related dependencies. Implement the `builder` method to define how dependencies should be bound within the scope.
|
||||
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().toInstance(ApiClientMock());
|
||||
bind<String>().toProvide(() => "Hello world!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Scope
|
||||
|
||||
A **Scope** manages a tree of modules and dependency instances. Scopes can be nested into hierarchies (parent-child), supporting modular app composition and context-specific overrides.
|
||||
|
||||
You typically work with the root scope, but can also create named subscopes as needed.
|
||||
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
// Open the main/root scope
|
||||
final rootScope = CherryPick.openRootScope();
|
||||
|
||||
// Install a custom module
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
// Resolve a dependency synchronously
|
||||
final str = rootScope.resolve<String>();
|
||||
|
||||
// Resolve a dependency asynchronously
|
||||
final result = await rootScope.resolveAsync<String>();
|
||||
|
||||
// Close the root scope once done
|
||||
CherryPick.closeRootScope();
|
||||
```
|
||||
|
||||
#### Working with Subscopes
|
||||
|
||||
```dart
|
||||
// Open a named child scope (e.g., for a feature/module)
|
||||
final subScope = rootScope.openSubScope('featureScope')
|
||||
..installModules([FeatureModule()]);
|
||||
|
||||
// Resolve from subScope, with fallback to parents if missing
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
```
|
||||
|
||||
### Dependency Lookup API
|
||||
|
||||
- `resolve<T>()` — Locates a dependency instance or throws if missing.
|
||||
- `resolveAsync<T>()` — Async variant for dependencies requiring async binding.
|
||||
- `tryResolve<T>()` — Returns `null` if not found (sync).
|
||||
- `tryResolveAsync<T>()` — Returns `null` async if not found.
|
||||
|
||||
Supports:
|
||||
- Synchronous and asynchronous dependencies
|
||||
- Named dependencies
|
||||
- Provider functions with and without runtime parameters
|
||||
|
||||
## Example Application
|
||||
|
||||
Below is a complete example illustrating modules, subscopes, async providers, and dependency resolution.
|
||||
|
||||
```dart
|
||||
import 'dart:async';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
|
||||
bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
|
||||
}
|
||||
}
|
||||
|
||||
class FeatureModule extends Module {
|
||||
final bool isMock;
|
||||
FeatureModule({required this.isMock});
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
// Async provider for DataRepository with named dependency selection
|
||||
bind<DataRepository>()
|
||||
.withName("networkRepo")
|
||||
.toProvideAsync(() async {
|
||||
final client = await Future.delayed(
|
||||
Duration(milliseconds: 100),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl",
|
||||
),
|
||||
);
|
||||
return NetworkDataRepository(client);
|
||||
})
|
||||
.singleton();
|
||||
|
||||
// Chained async provider for DataBloc
|
||||
bind<DataBloc>().toProvideAsync(
|
||||
() async {
|
||||
final repo = await currentScope.resolveAsync<DataRepository>(
|
||||
named: "networkRepo");
|
||||
return DataBloc(repo);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() async {
|
||||
final scope = CherryPick.openRootScope().installModules([AppModule()]);
|
||||
final featureScope = scope.openSubScope("featureScope")
|
||||
..installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
final dataBloc = await featureScope.resolveAsync<DataBloc>();
|
||||
dataBloc.data.listen(
|
||||
(d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'),
|
||||
onDone: () => print('DONE'),
|
||||
);
|
||||
|
||||
await dataBloc.fetchData();
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
Stream<String> get data => _dataController.stream;
|
||||
final StreamController<String> _dataController = StreamController.broadcast();
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
Future<void> fetchData() async {
|
||||
try {
|
||||
_dataController.sink.add(await _dataRepository.getData());
|
||||
} catch (e) {
|
||||
_dataController.sink.addError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_dataController.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class DataRepository {
|
||||
Future<String> getData();
|
||||
}
|
||||
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async =>
|
||||
await _apiClient.sendRequest(
|
||||
url: 'www.google.com',
|
||||
token: _token,
|
||||
requestBody: {'type': 'data'},
|
||||
);
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String? url, String? token, Map? requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Local Data';
|
||||
}
|
||||
}
|
||||
|
||||
class ApiClientImpl implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Network data';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- [x] Main Scope and Named Subscopes
|
||||
- [x] Named Instance Binding and Resolution
|
||||
- [x] Asynchronous and Synchronous Providers
|
||||
- [x] Providers Supporting Runtime Parameters
|
||||
- [x] Singleton Lifecycle Management
|
||||
- [x] Modular and Hierarchical Composition
|
||||
- [x] Null-safe Resolution (tryResolve/tryResolveAsync)
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).
|
||||
|
||||
## License
|
||||
|
||||
Licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
|
||||
---
|
||||
|
||||
**Important:** Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for specific language governing permissions and limitations under the License.
|
||||
|
||||
## Links
|
||||
|
||||
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
||||
@@ -1,30 +0,0 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
@@ -1,194 +0,0 @@
|
||||
# Quick start
|
||||
|
||||
## Main components DI
|
||||
|
||||
|
||||
### Binding
|
||||
|
||||
Binding is a custom instance configurator that contains methods for configuring a dependency.
|
||||
|
||||
There are two main methods for initializing a custom instance `toInstance ()` and `toProvide ()` and auxiliary `withName ()` and `singleton ()`.
|
||||
|
||||
`toInstance()` - takes a initialized instance
|
||||
|
||||
`toProvide()` - takes a `provider` function (instance constructor)
|
||||
|
||||
`withName()` - takes a string to name the instance. By this name, it will be possible to extract instance from the DI container
|
||||
|
||||
`singleton()` - sets a flag in the Binding that tells the DI container that there is only one dependency.
|
||||
|
||||
Example:
|
||||
|
||||
```dart
|
||||
// initializing a text string instance through a method toInstance()
|
||||
Binding<String>().toInstance("hello world");
|
||||
|
||||
// or
|
||||
|
||||
// initializing a text string instance
|
||||
Binding<String>().toProvide(() => "hello world");
|
||||
|
||||
// initializing an instance of a string named
|
||||
Binding<String>().withName("my_string").toInstance("hello world");
|
||||
// or
|
||||
Binding<String>().withName("my_string").toProvide(() => "hello world");
|
||||
|
||||
// instance initialization like singleton
|
||||
Binding<String>().toInstance("hello world");
|
||||
// or
|
||||
Binding<String>().toProvide(() => "hello world").singleton();
|
||||
|
||||
```
|
||||
|
||||
### Module
|
||||
|
||||
Module is a container of user instances, and on the basis of which the user can create their modules. The user in his module must implement the `void builder (Scope currentScope)` method.
|
||||
|
||||
|
||||
Example:
|
||||
|
||||
```dart
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().toInstance(ApiClientMock());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Scope
|
||||
|
||||
Scope is a container that stores the entire dependency tree (scope, modules, instances).
|
||||
Through the scope, you can access the custom `instance`, for this you need to call the `resolve<T>()` method and specify the type of the object, and you can also pass additional parameters.
|
||||
|
||||
Example:
|
||||
|
||||
```dart
|
||||
// open main scope
|
||||
final rootScope = Cherrypick.openRootScope();
|
||||
|
||||
// initializing scope with a custom module
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
// takes custom instance
|
||||
final str = rootScope.resolve<String>();
|
||||
// or
|
||||
final str = rootScope.tryResolve<String>();
|
||||
|
||||
// close main scope
|
||||
Cherrypick.closeRootScope();
|
||||
```
|
||||
|
||||
## Example app
|
||||
|
||||
|
||||
```dart
|
||||
import 'dart:async';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
|
||||
bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
|
||||
}
|
||||
}
|
||||
|
||||
class FeatureModule extends Module {
|
||||
bool isMock;
|
||||
|
||||
FeatureModule({required this.isMock});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<DataRepository>()
|
||||
.withName("networkRepo")
|
||||
.toProvide(
|
||||
() => NetworkDataRepository(
|
||||
currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl",
|
||||
),
|
||||
),
|
||||
)
|
||||
.singleton();
|
||||
bind<DataBloc>().toProvide(
|
||||
() => DataBloc(
|
||||
currentScope.resolve<DataRepository>(named: "networkRepo"),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() async {
|
||||
final scope = openRootScope().installModules([
|
||||
AppModule(),
|
||||
]);
|
||||
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
final dataBloc = subScope.resolve<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
|
||||
await dataBloc.fetchData();
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
Stream<String> get data => _dataController.stream;
|
||||
StreamController<String> _dataController = new StreamController.broadcast();
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
Future<void> fetchData() async {
|
||||
try {
|
||||
_dataController.sink.add(await _dataRepository.getData());
|
||||
} catch (e) {
|
||||
_dataController.sink.addError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_dataController.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class DataRepository {
|
||||
Future<String> getData();
|
||||
}
|
||||
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async => await _apiClient.sendRequest(
|
||||
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String url, String token, Map requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Local Data';
|
||||
}
|
||||
}
|
||||
|
||||
class ApiClientImpl implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Network data';
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,194 +0,0 @@
|
||||
# Быстрый старт
|
||||
|
||||
## Основные компоненты DI
|
||||
|
||||
|
||||
### Binding
|
||||
|
||||
Binding - по сути это конфигуратор для пользовательского instance, который соддержит методы для конфигурирования зависимости.
|
||||
|
||||
Есть два основных метода для инициализации пользовательского instance `toInstance()` и `toProvide()` и вспомогательных `withName()` и `singleton()`.
|
||||
|
||||
`toInstance()` - принимает готовый экземпляр
|
||||
|
||||
`toProvide()` - принимает функцию `provider` (конструктор экземпляра)
|
||||
|
||||
`withName()` - принимает строку для именования экземпляра. По этому имени можно будет извлечь instance из DI контейнера
|
||||
|
||||
`singleton()` - устанавливает флаг в Binding, который говорит DI контейнеру, что зависимость одна.
|
||||
|
||||
Пример:
|
||||
|
||||
```dart
|
||||
// инициализация экземпляра текстовой строки через метод toInstance()
|
||||
Binding<String>().toInstance("hello world");
|
||||
|
||||
// или
|
||||
|
||||
// инициализация экземпляра текстовой строки
|
||||
Binding<String>().toProvide(() => "hello world");
|
||||
|
||||
// инициализация экземпляра строки с именем
|
||||
Binding<String>().withName("my_string").toInstance("hello world");
|
||||
// или
|
||||
Binding<String>().withName("my_string").toProvide(() => "hello world");
|
||||
|
||||
// инициализация экземпляра, как сингелтон
|
||||
Binding<String>().toInstance("hello world");
|
||||
// или
|
||||
Binding<String>().toProvide(() => "hello world").singleton();
|
||||
|
||||
```
|
||||
|
||||
### Module
|
||||
|
||||
Module - это контейнер пользовательских instances, и на основе которого пользователь может создавать свои модули. Пользователь в своем модуле должен реализовать метод `void builder(Scope currentScope)`.
|
||||
|
||||
|
||||
Пример:
|
||||
|
||||
```dart
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().toInstance(ApiClientMock());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Scope
|
||||
|
||||
Scope - это контейнер, который хранит все дерево зависимостей (scope,modules,instances).
|
||||
Через scope можно получить доступ к `instance`, для этого нужно вызвать метод `resolve<T>()` и указать тип объекта, а так же можно передать дополнительные параметры.
|
||||
|
||||
Пример:
|
||||
|
||||
```dart
|
||||
// открыть главный scope
|
||||
final rootScope = CherryPick.openRootScope();
|
||||
|
||||
// инициализация scope пользовательским модулем
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
// получаем экземпляр класса
|
||||
final str = rootScope.resolve<String>();
|
||||
// или
|
||||
final str = rootScope.tryResolve<String>();
|
||||
|
||||
// закрыть главный scope
|
||||
Cherrypick.closeRootScope();
|
||||
```
|
||||
|
||||
## Пример приложения
|
||||
|
||||
|
||||
```dart
|
||||
import 'dart:async';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
|
||||
bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
|
||||
}
|
||||
}
|
||||
|
||||
class FeatureModule extends Module {
|
||||
bool isMock;
|
||||
|
||||
FeatureModule({required this.isMock});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<DataRepository>()
|
||||
.withName("networkRepo")
|
||||
.toProvide(
|
||||
() => NetworkDataRepository(
|
||||
currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl",
|
||||
),
|
||||
),
|
||||
)
|
||||
.singleton();
|
||||
bind<DataBloc>().toProvide(
|
||||
() => DataBloc(
|
||||
currentScope.resolve<DataRepository>(named: "networkRepo"),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() async {
|
||||
final scope = openRootScope().installModules([
|
||||
AppModule(),
|
||||
]);
|
||||
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
final dataBloc = subScope.resolve<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
|
||||
await dataBloc.fetchData();
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
Stream<String> get data => _dataController.stream;
|
||||
StreamController<String> _dataController = new StreamController.broadcast();
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
Future<void> fetchData() async {
|
||||
try {
|
||||
_dataController.sink.add(await _dataRepository.getData());
|
||||
} catch (e) {
|
||||
_dataController.sink.addError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_dataController.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class DataRepository {
|
||||
Future<String> getData();
|
||||
}
|
||||
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async => await _apiClient.sendRequest(
|
||||
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String url, String token, Map requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Local Data';
|
||||
}
|
||||
}
|
||||
|
||||
class ApiClientImpl implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Network data';
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,133 +0,0 @@
|
||||
# Example
|
||||
|
||||
pubspec.yaml:
|
||||
|
||||
```yaml
|
||||
name: example
|
||||
version: 1.0.0
|
||||
|
||||
environment:
|
||||
sdk: ">=2.12.0 <3.0.0"
|
||||
|
||||
|
||||
dependencies:
|
||||
cherrypick:
|
||||
path: ../
|
||||
|
||||
dev_dependencies:
|
||||
test: ^1.16.8
|
||||
```
|
||||
|
||||
main.dart:
|
||||
|
||||
```dart
|
||||
import 'dart:async';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:cherrypick/scope.dart';
|
||||
import 'package:cherrypick/module.dart';
|
||||
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
|
||||
bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
|
||||
}
|
||||
}
|
||||
|
||||
class FeatureModule extends Module {
|
||||
bool isMock;
|
||||
|
||||
FeatureModule({required this.isMock});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<DataRepository>()
|
||||
.withName("networkRepo")
|
||||
.toProvide(
|
||||
() => NetworkDataRepository(
|
||||
currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl",
|
||||
),
|
||||
),
|
||||
)
|
||||
.singleton();
|
||||
bind<DataBloc>().toProvide(
|
||||
() => DataBloc(
|
||||
currentScope.resolve<DataRepository>(named: "networkRepo"),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() async {
|
||||
final scope = openRootScope().installModules([
|
||||
AppModule(),
|
||||
]);
|
||||
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
final dataBloc = subScope.resolve<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
|
||||
await dataBloc.fetchData();
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
Stream<String> get data => _dataController.stream;
|
||||
StreamController<String> _dataController = new StreamController.broadcast();
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
Future<void> fetchData() async {
|
||||
try {
|
||||
_dataController.sink.add(await _dataRepository.getData());
|
||||
} catch (e) {
|
||||
_dataController.sink.addError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_dataController.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class DataRepository {
|
||||
Future<String> getData();
|
||||
}
|
||||
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async => await _apiClient.sendRequest(
|
||||
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String url, String token, Map requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Local Data';
|
||||
}
|
||||
}
|
||||
|
||||
class ApiClientImpl implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'Network data';
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,112 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
|
||||
bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
|
||||
}
|
||||
}
|
||||
|
||||
class FeatureModule extends Module {
|
||||
final bool isMock;
|
||||
|
||||
FeatureModule({required this.isMock});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
// Using toProvideAsync for async initialization
|
||||
bind<DataRepository>().withName("networkRepo").toProvideAsync(() async {
|
||||
final client = await Future.delayed(
|
||||
Duration(milliseconds: 100),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl"));
|
||||
return NetworkDataRepository(client);
|
||||
}).singleton();
|
||||
|
||||
// Asynchronous initialization of DataBloc
|
||||
bind<DataBloc>().toProvideAsync(
|
||||
() async {
|
||||
final repo = await currentScope.resolveAsync<DataRepository>(
|
||||
named: "networkRepo");
|
||||
return DataBloc(repo);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> main() async {
|
||||
try {
|
||||
final scope = openRootScope().installModules([
|
||||
AppModule(),
|
||||
]);
|
||||
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
// Asynchronous instance resolution
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
|
||||
await dataBloc.fetchData();
|
||||
} catch (e) {
|
||||
print('Error resolving dependency: $e');
|
||||
}
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
final StreamController<String> _dataController = StreamController.broadcast();
|
||||
Stream<String> get data => _dataController.stream;
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
Future<void> fetchData() async {
|
||||
try {
|
||||
_dataController.sink.add(await _dataRepository.getData());
|
||||
} catch (e) {
|
||||
_dataController.sink.addError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_dataController.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class DataRepository {
|
||||
Future<String> getData();
|
||||
}
|
||||
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async => await _apiClient.sendRequest(
|
||||
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({String url, String token, Map requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest({String? url, String? token, Map? requestBody}) async {
|
||||
return 'Local Data';
|
||||
}
|
||||
}
|
||||
|
||||
class ApiClientImpl implements ApiClient {
|
||||
@override
|
||||
Future sendRequest({String? url, String? token, Map? requestBody}) async {
|
||||
return 'Network data';
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
library;
|
||||
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
export 'package:cherrypick/src/binding.dart';
|
||||
export 'package:cherrypick/src/helper.dart';
|
||||
export 'package:cherrypick/src/module.dart';
|
||||
export 'package:cherrypick/src/scope.dart';
|
||||
@@ -1,190 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
enum Mode { simple, instance, providerInstance, providerInstanceWithParams }
|
||||
|
||||
typedef Provider<T> = T? Function();
|
||||
|
||||
typedef ProviderWithParams<T> = T Function(dynamic params);
|
||||
|
||||
typedef AsyncProvider<T> = Future<T> Function();
|
||||
|
||||
typedef AsyncProviderWithParams<T> = Future<T> Function(dynamic params);
|
||||
|
||||
/// RU: Класс Binding<T> настраивает параметры экземпляра.
|
||||
/// ENG: The Binding<T> class configures the settings for the instance.
|
||||
///
|
||||
class Binding<T> {
|
||||
late Mode _mode;
|
||||
late Type _key;
|
||||
late String _name;
|
||||
T? _instance;
|
||||
Future<T>? _instanceAsync;
|
||||
Provider<T>? _provider;
|
||||
ProviderWithParams<T>? _providerWithParams;
|
||||
|
||||
AsyncProvider<T>? asyncProvider;
|
||||
AsyncProviderWithParams<T>? asyncProviderWithParams;
|
||||
|
||||
late bool _isSingleton = false;
|
||||
late bool _isNamed = false;
|
||||
|
||||
Binding() {
|
||||
_mode = Mode.simple;
|
||||
_key = T;
|
||||
}
|
||||
|
||||
/// RU: Метод возвращает [Mode] экземпляра.
|
||||
/// ENG: The method returns the [Mode] of the instance.
|
||||
///
|
||||
/// return [Mode]
|
||||
Mode get mode => _mode;
|
||||
|
||||
/// RU: Метод возвращает тип экземпляра.
|
||||
/// ENG: The method returns the type of the instance.
|
||||
///
|
||||
/// return [Type]
|
||||
Type get key => _key;
|
||||
|
||||
/// RU: Метод возвращает имя экземпляра.
|
||||
/// ENG: The method returns the name of the instance.
|
||||
///
|
||||
/// return [String]
|
||||
String get name => _name;
|
||||
|
||||
/// RU: Метод проверяет сингелтон экземпляр или нет.
|
||||
/// ENG: The method checks the singleton instance or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isSingleton => _isSingleton;
|
||||
|
||||
/// RU: Метод проверяет именован экземпляр или нет.
|
||||
/// ENG: The method checks whether the instance is named or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isNamed => _isNamed;
|
||||
|
||||
/// RU: Добавляет имя для экземляпя [value].
|
||||
/// ENG: Added name for instance [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> withName(String name) {
|
||||
_name = name;
|
||||
_isNamed = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра [value].
|
||||
/// ENG: Initialization instance [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toInstance(T value) {
|
||||
_mode = Mode.instance;
|
||||
_instance = value;
|
||||
_isSingleton = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра [value].
|
||||
/// ENG: Initialization instance [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toInstanceAsync(Future<T> value) {
|
||||
_mode = Mode.instance;
|
||||
_instanceAsync = value;
|
||||
_isSingleton = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value].
|
||||
/// ENG: Initialization instance via provider [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvide(Provider<T> value) {
|
||||
_mode = Mode.providerInstance;
|
||||
_provider = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value].
|
||||
/// ENG: Initialization instance via provider [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideAsync(AsyncProvider<T> provider) {
|
||||
_mode = Mode.providerInstance;
|
||||
asyncProvider = provider;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value] c динамическим параметром.
|
||||
/// ENG: Initialization instance via provider [value] with a dynamic param.
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideWithParams(ProviderWithParams<T> value) {
|
||||
_mode = Mode.providerInstanceWithParams;
|
||||
_providerWithParams = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляра через асинхронный провайдер [value] с динамическим параметром.
|
||||
/// ENG: Initializes the instance via async provider [value] with a dynamic param.
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideAsyncWithParams(AsyncProviderWithParams<T> provider) {
|
||||
_mode = Mode.providerInstanceWithParams;
|
||||
asyncProviderWithParams = provider;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра как сингелтон [value].
|
||||
/// ENG: Initialization instance as a singelton [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> singleton() {
|
||||
_isSingleton = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
T? get instance => _instance;
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
Future<T>? get instanceAsync => _instanceAsync;
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
T? get provider {
|
||||
if (_isSingleton) {
|
||||
_instance ??= _provider?.call();
|
||||
return _instance;
|
||||
}
|
||||
return _provider?.call();
|
||||
}
|
||||
|
||||
/// RU: Поиск экземпляра с параметром.
|
||||
///
|
||||
/// ENG: Resolve instance with [params].
|
||||
///
|
||||
/// return [T]
|
||||
T? providerWithParams(dynamic params) {
|
||||
return _providerWithParams?.call(params);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
|
||||
abstract class Factory<T> {
|
||||
T createInstance(Scope scope);
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
Scope? _rootScope;
|
||||
|
||||
class CherryPick {
|
||||
/// RU: Метод открывает главный [Scope].
|
||||
/// ENG: The method opens the main [Scope].
|
||||
///
|
||||
/// return
|
||||
static Scope openRootScope() {
|
||||
_rootScope ??= Scope(null);
|
||||
return _rootScope!;
|
||||
}
|
||||
|
||||
/// RU: Метод закрывает главный [Scope].
|
||||
/// ENG: The method close the main [Scope].
|
||||
///
|
||||
///
|
||||
static void closeRootScope() {
|
||||
if (_rootScope != null) {
|
||||
_rootScope = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Метод открывает дочерний [Scope].
|
||||
/// ENG: The method open the child [Scope].
|
||||
///
|
||||
/// Дочерний [Scope] открывается с [scopeName]
|
||||
/// Child [Scope] open with [scopeName]
|
||||
///
|
||||
/// Example:
|
||||
/// ```
|
||||
/// final String scopeName = 'firstScope.secondScope';
|
||||
/// final subScope = CherryPick.openScope(scopeName);
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
@experimental
|
||||
static Scope openScope({String scopeName = '', String separator = '.'}) {
|
||||
if (scopeName.isEmpty) {
|
||||
return openRootScope();
|
||||
}
|
||||
|
||||
final nameParts = scopeName.split(separator);
|
||||
if (nameParts.isEmpty) {
|
||||
throw Exception('Can not open sub scope because scopeName can not split');
|
||||
}
|
||||
|
||||
return nameParts.fold(
|
||||
openRootScope(),
|
||||
(Scope previousValue, String element) =>
|
||||
previousValue.openSubScope(element));
|
||||
}
|
||||
|
||||
/// RU: Метод открывает дочерний [Scope].
|
||||
/// ENG: The method open the child [Scope].
|
||||
///
|
||||
/// Дочерний [Scope] открывается с [scopeName]
|
||||
/// Child [Scope] open with [scopeName]
|
||||
///
|
||||
/// Example:
|
||||
/// ```
|
||||
/// final String scopeName = 'firstScope.secondScope';
|
||||
/// final subScope = CherryPick.closeScope(scopeName);
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
@experimental
|
||||
static void closeScope({String scopeName = '', String separator = '.'}) {
|
||||
if (scopeName.isEmpty) {
|
||||
closeRootScope();
|
||||
}
|
||||
|
||||
final nameParts = scopeName.split(separator);
|
||||
if (nameParts.isEmpty) {
|
||||
throw Exception(
|
||||
'Can not close sub scope because scopeName can not split');
|
||||
}
|
||||
|
||||
if (nameParts.length > 1) {
|
||||
final lastPart = nameParts.removeLast();
|
||||
|
||||
final scope = nameParts.fold(
|
||||
openRootScope(),
|
||||
(Scope previousValue, String element) =>
|
||||
previousValue.openSubScope(element));
|
||||
scope.closeSubScope(lastPart);
|
||||
} else {
|
||||
openRootScope().closeSubScope(nameParts[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
|
||||
/// RU: Класс Module является основой для пользовательских модулей.
|
||||
/// Этот класс нужен для инициализации [Scope].
|
||||
///
|
||||
/// RU: The Module class is the basis for custom modules.
|
||||
/// This class is needed to initialize [Scope].
|
||||
///
|
||||
abstract class Module {
|
||||
final Set<Binding> _bindingSet = HashSet();
|
||||
|
||||
/// RU: Метод добавляет в коллекцию модуля [Binding] экземпляр.
|
||||
///
|
||||
/// ENG: The method adds an instance to the collection of the [Binding] module.
|
||||
///
|
||||
/// return [Binding<T>]
|
||||
Binding<T> bind<T>() {
|
||||
final binding = Binding<T>();
|
||||
_bindingSet.add(binding);
|
||||
return binding;
|
||||
}
|
||||
|
||||
/// RU: Метод возвращает коллекцию [Binding] экземпляров.
|
||||
///
|
||||
/// ENG: The method returns a collection of [Binding] instances.
|
||||
///
|
||||
/// return [Set<Binding>]
|
||||
Set<Binding> get bindingSet => _bindingSet;
|
||||
|
||||
/// RU: Абстрактный метод для инициализации пользовательских экземпляров.
|
||||
/// В этом методе осуществляется конфигурация зависимостей.
|
||||
///
|
||||
/// ENG: Abstract method for initializing custom instances.
|
||||
/// This method configures dependencies.
|
||||
///
|
||||
/// return [void]
|
||||
void builder(Scope currentScope);
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
import 'package:cherrypick/src/module.dart';
|
||||
|
||||
Scope openRootScope() => Scope(null);
|
||||
|
||||
class Scope {
|
||||
final Scope? _parentScope;
|
||||
|
||||
/// RU: Метод возвращает родительский [Scope].
|
||||
///
|
||||
/// ENG: The method returns the parent [Scope].
|
||||
///
|
||||
/// return [Scope]
|
||||
Scope? get parentScope => _parentScope;
|
||||
|
||||
final Map<String, Scope> _scopeMap = HashMap();
|
||||
|
||||
Scope(this._parentScope);
|
||||
|
||||
final Set<Module> _modulesList = HashSet();
|
||||
|
||||
/// RU: Метод открывает дочерний (дополнительный) [Scope].
|
||||
///
|
||||
/// ENG: The method opens child (additional) [Scope].
|
||||
///
|
||||
/// return [Scope]
|
||||
Scope openSubScope(String name) {
|
||||
if (!_scopeMap.containsKey(name)) {
|
||||
_scopeMap[name] = Scope(this);
|
||||
}
|
||||
return _scopeMap[name]!;
|
||||
}
|
||||
|
||||
/// RU: Метод закрывает дочерний (дополнительный) [Scope].
|
||||
///
|
||||
/// ENG: The method closes child (additional) [Scope].
|
||||
///
|
||||
/// return [Scope]
|
||||
void closeSubScope(String name) {
|
||||
_scopeMap.remove(name);
|
||||
}
|
||||
|
||||
/// RU: Метод инициализирует пользовательские модули в [Scope].
|
||||
///
|
||||
/// ENG: The method initializes custom modules in [Scope].
|
||||
///
|
||||
/// return [Scope]
|
||||
Scope installModules(List<Module> modules) {
|
||||
_modulesList.addAll(modules);
|
||||
for (var module in modules) {
|
||||
module.builder(this);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Метод удаляет пользовательские модули из [Scope].
|
||||
///
|
||||
/// ENG: This method removes custom modules from [Scope].
|
||||
///
|
||||
/// return [Scope]
|
||||
Scope dropModules() {
|
||||
// [AlexeyYuPopkov](https://github.com/AlexeyYuPopkov) Thank you for the [Removed exception "ConcurrentModificationError"](https://github.com/pese-git/cherrypick/pull/2)
|
||||
_modulesList.clear();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Возвращает найденную зависимость, определенную параметром типа [T].
|
||||
/// Выдает [StateError], если зависимость не может быть разрешена.
|
||||
/// Если вы хотите получить [null], если зависимость не может быть найдена,
|
||||
/// то используйте вместо этого [tryResolve]
|
||||
/// return - возвращает объект типа [T] или [StateError]
|
||||
///
|
||||
/// ENG: Returns the found dependency specified by the type parameter [T].
|
||||
/// Throws [StateError] if the dependency cannot be resolved.
|
||||
/// If you want to get [null] if the dependency cannot be found then use [tryResolve] instead
|
||||
/// return - returns an object of type [T] or [StateError]
|
||||
///
|
||||
T resolve<T>({String? named, dynamic params}) {
|
||||
var resolved = tryResolve<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
} else {
|
||||
throw StateError(
|
||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Возвращает найденную зависимость типа [T] или null, если она не может быть найдена.
|
||||
/// ENG: Returns found dependency of type [T] or null if it cannot be found.
|
||||
///
|
||||
T? tryResolve<T>({String? named, dynamic params}) {
|
||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
||||
if (_modulesList.isNotEmpty) {
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
if (binding.key == T &&
|
||||
((!binding.isNamed && named == null) ||
|
||||
(binding.isNamed && named == binding.name))) {
|
||||
switch (binding.mode) {
|
||||
case Mode.instance:
|
||||
return binding.instance;
|
||||
case Mode.providerInstance:
|
||||
return binding.provider;
|
||||
case Mode.providerInstanceWithParams:
|
||||
if (params == null) {
|
||||
throw StateError('Param is null. Maybe you forget pass it');
|
||||
}
|
||||
return binding.providerWithParams(params);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
return _parentScope?.tryResolve(named: named, params: params);
|
||||
}
|
||||
|
||||
/// RU: Асинхронно возвращает найденную зависимость, определенную параметром типа [T].
|
||||
/// Выдает [StateError], если зависимость не может быть разрешена.
|
||||
/// Если хотите получить [null], если зависимость не может быть найдена, используйте [tryResolveAsync].
|
||||
/// return - возвращает объект типа [T] or [StateError]
|
||||
///
|
||||
/// ENG: Asynchronously returns the found dependency specified by the type parameter [T].
|
||||
/// Throws [StateError] if the dependency cannot be resolved.
|
||||
/// If you want to get [null] if the dependency cannot be found, use [tryResolveAsync] instead.
|
||||
/// return - returns an object of type [T] or [StateError]
|
||||
///
|
||||
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
|
||||
var resolved = await tryResolveAsync<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
} else {
|
||||
throw StateError(
|
||||
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
}
|
||||
|
||||
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
|
||||
if (_modulesList.isNotEmpty) {
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
if (binding.key == T &&
|
||||
((!binding.isNamed && named == null) ||
|
||||
(binding.isNamed && named == binding.name))) {
|
||||
if (binding.instanceAsync != null) {
|
||||
return await binding.instanceAsync;
|
||||
}
|
||||
|
||||
if (binding.asyncProvider != null) {
|
||||
return await binding.asyncProvider?.call();
|
||||
}
|
||||
|
||||
if (binding.asyncProviderWithParams != null) {
|
||||
if (params == null) {
|
||||
throw StateError('Param is null. Maybe you forget pass it');
|
||||
}
|
||||
return await binding.asyncProviderWithParams!(params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return _parentScope?.tryResolveAsync(named: named, params: params);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
name: cherrypick
|
||||
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
|
||||
version: 2.2.0-dev.1
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
dependencies:
|
||||
meta: ^1.3.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
test: ^1.25.15
|
||||
|
||||
mockito: ^5.0.6
|
||||
melos: ^6.3.2
|
||||
@@ -1,271 +0,0 @@
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
// --- Instance binding (synchronous) ---
|
||||
group('Instance Binding (toInstance)', () {
|
||||
group('Without name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.instance, null);
|
||||
});
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.mode, Mode.instance);
|
||||
});
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Stores value', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.instance, 5);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>().withName('n');
|
||||
expect(binding.instance, null);
|
||||
});
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.mode, Mode.instance);
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.key, int);
|
||||
});
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Stores value', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.instance, 5);
|
||||
});
|
||||
|
||||
test('Sets name', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.name, 'n');
|
||||
});
|
||||
});
|
||||
|
||||
test('Multiple toInstance calls change value', () {
|
||||
final binding = Binding<int>().toInstance(1).toInstance(2);
|
||||
expect(binding.instance, 2);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Instance binding (asynchronous) ---
|
||||
group('Async Instance Binding (toInstanceAsync)', () {
|
||||
test('Resolves instanceAsync with expected value', () async {
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(42));
|
||||
expect(await binding.instanceAsync, 42);
|
||||
});
|
||||
|
||||
test('Does not affect instance', () {
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(5));
|
||||
expect(binding.instance, null);
|
||||
});
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(5));
|
||||
expect(binding.mode, Mode.instance);
|
||||
});
|
||||
|
||||
test('isSingleton is true after toInstanceAsync', () {
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(5));
|
||||
expect(binding.isSingleton, isTrue);
|
||||
});
|
||||
|
||||
test('Composes with withName', () async {
|
||||
final binding = Binding<int>()
|
||||
.withName('asyncValue')
|
||||
.toInstanceAsync(Future.value(7));
|
||||
expect(binding.isNamed, isTrue);
|
||||
expect(binding.name, 'asyncValue');
|
||||
expect(await binding.instanceAsync, 7);
|
||||
});
|
||||
|
||||
test('Keeps value after multiple awaits', () async {
|
||||
final binding = Binding<int>().toInstanceAsync(Future.value(123));
|
||||
final result1 = await binding.instanceAsync;
|
||||
final result2 = await binding.instanceAsync;
|
||||
expect(result1, equals(result2));
|
||||
});
|
||||
});
|
||||
|
||||
// --- Provider binding (synchronous) ---
|
||||
group('Provider Binding (toProvide)', () {
|
||||
group('Without name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('isSingleton is false by default', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.isSingleton, false);
|
||||
});
|
||||
|
||||
test('Returns provided value', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>().withName('n');
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.key, int);
|
||||
});
|
||||
|
||||
test('isSingleton is false by default', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.isSingleton, false);
|
||||
});
|
||||
|
||||
test('Returns provided value', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
|
||||
test('Sets name', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.name, 'n');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// --- Async provider binding ---
|
||||
group('Async Provider Binding', () {
|
||||
test('Resolves asyncProvider value', () async {
|
||||
final binding = Binding<int>().toProvideAsync(() async => 5);
|
||||
expect(await binding.asyncProvider?.call(), 5);
|
||||
});
|
||||
|
||||
test('Resolves asyncProviderWithParams value', () async {
|
||||
final binding = Binding<int>()
|
||||
.toProvideAsyncWithParams((param) async => 5 + (param as int));
|
||||
expect(await binding.asyncProviderWithParams?.call(3), 8);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Singleton provider binding ---
|
||||
group('Singleton Provider Binding', () {
|
||||
group('Without name', () {
|
||||
test('Returns null if no provider set', () {
|
||||
final binding = Binding<int>().singleton();
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().toProvide(() => 5).singleton();
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding = Binding<int>().toProvide(() => 5).singleton();
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Returns singleton value', () {
|
||||
final binding = Binding<int>().toProvide(() => 5).singleton();
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
|
||||
test('Returns same value each call and provider only called once', () {
|
||||
int counter = 0;
|
||||
final binding = Binding<int>().toProvide(() {
|
||||
counter++;
|
||||
return counter;
|
||||
}).singleton();
|
||||
|
||||
final first = binding.provider;
|
||||
final second = binding.provider;
|
||||
expect(first, equals(second));
|
||||
expect(counter, 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name', () {
|
||||
test('Returns null if no provider set', () {
|
||||
final binding = Binding<int>().withName('n').singleton();
|
||||
expect(binding.provider, null);
|
||||
});
|
||||
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('Sets key', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.key, int);
|
||||
});
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Returns singleton value', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.provider, 5);
|
||||
});
|
||||
|
||||
test('Sets name', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.name, 'n');
|
||||
});
|
||||
});
|
||||
|
||||
test('Chained withName and singleton preserves mode', () {
|
||||
final binding =
|
||||
Binding<int>().toProvide(() => 3).withName("named").singleton();
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
});
|
||||
|
||||
// --- WithName / Named binding, isNamed, edge-cases ---
|
||||
group('Named binding & helpers', () {
|
||||
test('withName sets isNamed true and stores name', () {
|
||||
final binding = Binding<int>().withName('foo');
|
||||
expect(binding.isNamed, true);
|
||||
expect(binding.name, 'foo');
|
||||
});
|
||||
|
||||
test('providerWithParams returns null if not set', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.providerWithParams(123), null);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
import 'package:cherrypick/src/module.dart';
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
// --------------------------------------------------------------------------
|
||||
group('Scope & Subscope Management', () {
|
||||
test('Scope has no parent if constructed with null', () {
|
||||
final scope = Scope(null);
|
||||
expect(scope.parentScope, null);
|
||||
});
|
||||
|
||||
test('Can open and retrieve the same subScope by key', () {
|
||||
final scope = Scope(null);
|
||||
final subScope = scope.openSubScope('subScope');
|
||||
expect(scope.openSubScope('subScope'), subScope);
|
||||
});
|
||||
|
||||
test('closeSubScope removes subscope so next openSubScope returns new', () {
|
||||
final scope = Scope(null);
|
||||
final subScope = scope.openSubScope("child");
|
||||
expect(scope.openSubScope("child"), same(subScope));
|
||||
scope.closeSubScope("child");
|
||||
final newSubScope = scope.openSubScope("child");
|
||||
expect(newSubScope, isNot(same(subScope)));
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Dependency Resolution (standard)', () {
|
||||
test("Throws StateError if value can't be resolved", () {
|
||||
final scope = Scope(null);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test('Resolves value after adding a dependency', () {
|
||||
final expectedValue = 'test string';
|
||||
final scope = Scope(null)
|
||||
.installModules([TestModule<String>(value: expectedValue)]);
|
||||
expect(scope.resolve<String>(), expectedValue);
|
||||
});
|
||||
|
||||
test('Returns a value from parent scope', () {
|
||||
final expectedValue = 5;
|
||||
final parentScope = Scope(null);
|
||||
final scope = Scope(parentScope);
|
||||
|
||||
parentScope.installModules([TestModule<int>(value: expectedValue)]);
|
||||
|
||||
expect(scope.resolve<int>(), expectedValue);
|
||||
});
|
||||
|
||||
test('Returns several values from parent container', () {
|
||||
final expectedIntValue = 5;
|
||||
final expectedStringValue = 'Hello world';
|
||||
final parentScope = Scope(null).installModules([
|
||||
TestModule<int>(value: expectedIntValue),
|
||||
TestModule<String>(value: expectedStringValue)
|
||||
]);
|
||||
final scope = Scope(parentScope);
|
||||
|
||||
expect(scope.resolve<int>(), expectedIntValue);
|
||||
expect(scope.resolve<String>(), expectedStringValue);
|
||||
});
|
||||
|
||||
test("Throws StateError if parent hasn't value too", () {
|
||||
final parentScope = Scope(null);
|
||||
final scope = Scope(parentScope);
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test("After dropModules resolves fail", () {
|
||||
final scope = Scope(null)..installModules([TestModule<int>(value: 5)]);
|
||||
expect(scope.resolve<int>(), 5);
|
||||
scope.dropModules();
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Named Dependencies', () {
|
||||
test('Resolve named binding', () {
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
TestModule<String>(value: "first"),
|
||||
TestModule<String>(value: "second", name: "special")
|
||||
]);
|
||||
expect(scope.resolve<String>(named: "special"), "second");
|
||||
expect(scope.resolve<String>(), "first");
|
||||
});
|
||||
|
||||
test('Named binding does not clash with unnamed', () {
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
TestModule<String>(value: "foo", name: "bar"),
|
||||
]);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
expect(scope.resolve<String>(named: "bar"), "foo");
|
||||
});
|
||||
|
||||
test("tryResolve returns null for missing named", () {
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
TestModule<String>(value: "foo"),
|
||||
]);
|
||||
expect(scope.tryResolve<String>(named: "bar"), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Provider with parameters', () {
|
||||
test('Resolve dependency using providerWithParams', () {
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvideWithParams((param) => (param as int) * 2);
|
||||
}),
|
||||
]);
|
||||
expect(scope.resolve<int>(params: 3), 6);
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Async Resolution', () {
|
||||
test('Resolve async instance', () async {
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<String>().toInstanceAsync(Future.value('async value'));
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<String>(), "async value");
|
||||
});
|
||||
|
||||
test('Resolve async provider', () async {
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvideAsync(() async => 7);
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<int>(), 7);
|
||||
});
|
||||
|
||||
test('Resolve async provider with param', () async {
|
||||
final scope = Scope(null)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvideAsyncWithParams((x) async => (x as int) * 3);
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<int>(params: 2), 6);
|
||||
expect(() => scope.resolveAsync<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test('tryResolveAsync returns null for missing', () async {
|
||||
final scope = Scope(null);
|
||||
final result = await scope.tryResolveAsync<String>();
|
||||
expect(result, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Optional resolution and error handling', () {
|
||||
test("tryResolve returns null for missing dependency", () {
|
||||
final scope = Scope(null);
|
||||
expect(scope.tryResolve<int>(), isNull);
|
||||
});
|
||||
|
||||
// Не реализован:
|
||||
// test("Container bind() throws state error (if it's parent already has a resolver)", () {
|
||||
// final parentScope = new Scope(null).installModules([TestModule<String>(value: "string one")]);
|
||||
// final scope = new Scope(parentScope);
|
||||
|
||||
// expect(
|
||||
// () => scope.installModules([TestModule<String>(value: "string two")]),
|
||||
// throwsA(isA<StateError>()));
|
||||
// });
|
||||
});
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Вспомогательные модули
|
||||
|
||||
class TestModule<T> extends Module {
|
||||
final T value;
|
||||
final String? name;
|
||||
|
||||
TestModule({required this.value, this.name});
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
if (name == null) {
|
||||
bind<T>().toInstance(value);
|
||||
} else {
|
||||
bind<T>().withName(name!).toInstance(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Вспомогательный модуль для подстановки builder'а через конструктор
|
||||
class _InlineModule extends Module {
|
||||
final void Function(Module, Scope) _builder;
|
||||
_InlineModule(this._builder);
|
||||
|
||||
@override
|
||||
void builder(Scope s) => _builder(this, s);
|
||||
}
|
||||
26
cherrypick_annotations/.gitignore
vendored
26
cherrypick_annotations/.gitignore
vendored
@@ -1,26 +0,0 @@
|
||||
# See https://www.dartlang.org/guides/libraries/private-files
|
||||
|
||||
# Files and directories created by pub
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
||||
# If you're building an application, you may want to check-in your pubspec.lock
|
||||
pubspec.lock
|
||||
|
||||
# Directory created by dartdoc
|
||||
# If you don't generate documentation locally you can remove this line.
|
||||
doc/api/
|
||||
|
||||
# Avoid committing generated Javascript files:
|
||||
*.dart.js
|
||||
*.info.json # Produced by the --dump-info flag.
|
||||
*.js # When generated by dart2js. Don't specify *.js if your
|
||||
# project includes source files written in JavaScript.
|
||||
*.js_
|
||||
*.js.deps
|
||||
*.js.map
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
|
||||
melos_cherrypick_annotations.iml
|
||||
@@ -1,15 +0,0 @@
|
||||
## 1.1.0-dev.1
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
## 1.1.0-dev.0
|
||||
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- Initial version.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,229 +0,0 @@
|
||||
# cherrypick_annotations
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
A lightweight set of Dart annotations for dependency injection (DI) frameworks and code generation, inspired by modern approaches like Dagger and Injectable. Optimized for use with [`cherrypick_generator`](https://pub.dev/packages/cherrypick_generator).
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **@module** – Marks a class as a DI module for service/provider registration.
|
||||
- **@singleton** – Declares that a method or class should be provided as a singleton.
|
||||
- **@instance** – Marks a method or class so that a new instance is provided on each request.
|
||||
- **@provide** – Marks a method whose return value should be registered as a provider, supporting DI into its parameters.
|
||||
- **@named** – Assigns a string name to a binding for keyed resolution and injection.
|
||||
- **@params** – Indicates that a parameter should be injected with runtime-supplied arguments.
|
||||
- **@injectable** – Marks a class as eligible for automatic field injection. Fields annotated with `@inject` will be injected by the code generator.
|
||||
- **@inject** – Marks a field to be automatically injected by the code generator.
|
||||
- **@scope** – Declares the DI scope from which a dependency should be resolved for a field.
|
||||
|
||||
These annotations streamline DI configuration and serve as markers for code generation tools such as [`cherrypick_generator`](https://pub.dev/packages/cherrypick_generator).
|
||||
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### 1. Add dependency
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick_annotations: ^latest
|
||||
```
|
||||
|
||||
Add as a `dev_dependency` for code generation:
|
||||
|
||||
```yaml
|
||||
dev_dependencies:
|
||||
cherrypick_generator: ^latest
|
||||
build_runner: ^latest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Annotate your DI modules, providers, and injectable classes
|
||||
|
||||
#### **Module and Provider Example**
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@module()
|
||||
abstract class AppModule {
|
||||
@singleton()
|
||||
Dio dio() => Dio();
|
||||
|
||||
@named('baseUrl')
|
||||
String baseUrl() => 'https://api.example.com';
|
||||
|
||||
@instance()
|
||||
Foo foo() => Foo();
|
||||
|
||||
@provide()
|
||||
Bar bar(Foo foo) => Bar(foo);
|
||||
|
||||
@provide()
|
||||
String greet(@params() dynamic params) => 'Hello $params';
|
||||
}
|
||||
```
|
||||
|
||||
With `cherrypick_generator`, code like the following will be generated:
|
||||
|
||||
```dart
|
||||
final class $AppModule extends AppModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<Dio>().toProvide(() => dio()).singleton();
|
||||
bind<String>().toProvide(() => baseUrl()).withName('baseUrl');
|
||||
bind<Foo>().toInstance(foo());
|
||||
bind<Bar>().toProvide(() => bar(currentScope.resolve<Foo>()));
|
||||
bind<String>().toProvideWithParams((args) => greet(args));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### **Field Injection Example**
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@injectable()
|
||||
class ProfileView with _$ProfileView{
|
||||
@inject()
|
||||
late final AuthService auth;
|
||||
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager manager;
|
||||
|
||||
@inject()
|
||||
@named('admin')
|
||||
late final UserService adminUserService;
|
||||
}
|
||||
```
|
||||
|
||||
The code generator produces a mixin (simplified):
|
||||
|
||||
```dart
|
||||
mixin _$ProfileView {
|
||||
void _inject(ProfileView instance) {
|
||||
instance.auth = CherryPick.openRootScope().resolve<AuthService>();
|
||||
instance.manager = CherryPick.openScope(scopeName: 'profile').resolve<ProfileManager>();
|
||||
instance.adminUserService = CherryPick.openRootScope().resolve<UserService>(named: 'admin');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Annotation Reference
|
||||
|
||||
### `@injectable`
|
||||
|
||||
```dart
|
||||
@injectable()
|
||||
class MyWidget { ... }
|
||||
```
|
||||
Marks a class as injectable for CherryPick DI. The code generator will generate a mixin to perform automatic injection of fields marked with `@inject()`.
|
||||
|
||||
---
|
||||
|
||||
### `@inject`
|
||||
|
||||
```dart
|
||||
@inject()
|
||||
late final SomeService service;
|
||||
```
|
||||
Applied to a field to request automatic injection of the dependency using the CherryPick DI framework.
|
||||
|
||||
---
|
||||
|
||||
### `@scope`
|
||||
|
||||
```dart
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager manager;
|
||||
```
|
||||
Specifies the scope from which the dependency should be resolved for an injected field.
|
||||
|
||||
---
|
||||
|
||||
### `@module`
|
||||
|
||||
```dart
|
||||
@module()
|
||||
abstract class AppModule {}
|
||||
```
|
||||
Use on classes to mark them as a DI module. This is the root for registering your dependency providers.
|
||||
|
||||
---
|
||||
|
||||
### `@singleton`
|
||||
|
||||
```dart
|
||||
@singleton()
|
||||
Dio dio() => Dio();
|
||||
```
|
||||
Use on methods or classes to provide a singleton instance (the same instance is reused).
|
||||
|
||||
---
|
||||
|
||||
### `@instance`
|
||||
|
||||
```dart
|
||||
@instance()
|
||||
Foo foo() => Foo();
|
||||
```
|
||||
Use on methods or classes to provide a new instance on each request (not a singleton).
|
||||
|
||||
---
|
||||
|
||||
### `@provide`
|
||||
|
||||
```dart
|
||||
@provide()
|
||||
Bar bar(Foo foo) => Bar(foo);
|
||||
```
|
||||
Use on methods to indicate they provide a dependency to the DI module. Dependencies listed as parameters (e.g., `foo`) are resolved and injected.
|
||||
|
||||
---
|
||||
|
||||
### `@named`
|
||||
|
||||
```dart
|
||||
@named('token')
|
||||
String token() => 'abc';
|
||||
```
|
||||
Assigns a name to a binding for keyed injection or resolution.
|
||||
Can be used on both provider methods and fields.
|
||||
|
||||
---
|
||||
|
||||
### `@params`
|
||||
|
||||
```dart
|
||||
@provide()
|
||||
String greet(@params() dynamic params) => 'Hello $params';
|
||||
```
|
||||
Indicates that this parameter should receive runtime-supplied arguments during dependency resolution.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Licensed under the [Apache License 2.0](LICENSE).
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
Pull requests and feedback are welcome!
|
||||
|
||||
---
|
||||
|
||||
## Author
|
||||
|
||||
Sergey Penkovsky (<sergey.penkovsky@gmail.com>)
|
||||
@@ -1,30 +0,0 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
@@ -1,24 +0,0 @@
|
||||
library;
|
||||
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
export 'src/module.dart';
|
||||
export 'src/provide.dart';
|
||||
export 'src/instance.dart';
|
||||
export 'src/singleton.dart';
|
||||
export 'src/named.dart';
|
||||
export 'src/params.dart';
|
||||
export 'src/inject.dart';
|
||||
export 'src/injectable.dart';
|
||||
export 'src/scope.dart';
|
||||
@@ -1,34 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Annotation for field injection in CherryPick DI framework.
|
||||
/// Apply this to a field, and the code generator will automatically inject
|
||||
/// the appropriate dependency into it.
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// Аннотация для внедрения зависимости в поле через фреймворк CherryPick DI.
|
||||
/// Поместите её на поле класса — генератор кода автоматически подставит нужную зависимость.
|
||||
///
|
||||
/// Example / Пример:
|
||||
/// ```dart
|
||||
/// @inject()
|
||||
/// late final SomeService service;
|
||||
/// ```
|
||||
@experimental
|
||||
// ignore: camel_case_types
|
||||
final class inject {
|
||||
const inject();
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks a class as injectable for the CherryPick dependency injection framework.
|
||||
/// If a class is annotated with [@injectable()], the code generator will
|
||||
/// create a mixin to perform automatic injection of fields marked with [@inject].
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// Помечает класс как внедряемый для фреймворка внедрения зависимостей CherryPick.
|
||||
/// Если класс помечен аннотацией [@injectable()], генератор создаст миксин
|
||||
/// для автоматического внедрения полей, отмеченных [@inject].
|
||||
///
|
||||
/// Example / Пример:
|
||||
/// ```dart
|
||||
/// @injectable()
|
||||
/// class MyWidget extends StatelessWidget {
|
||||
/// @inject()
|
||||
/// late final MyService service;
|
||||
/// }
|
||||
/// ```
|
||||
@experimental
|
||||
// ignore: camel_case_types
|
||||
final class injectable {
|
||||
const injectable();
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to specify that a new instance should be provided on each request.
|
||||
///
|
||||
/// Use the `@instance()` annotation for methods or classes in your DI module
|
||||
/// to declare that the DI container must create a new object every time
|
||||
/// the dependency is injected (i.e., no singleton behavior).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @instance()
|
||||
/// Foo foo() => Foo();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This will generate:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Foo>().toInstance(() => foo());
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для создания нового экземпляра при каждом запросе.
|
||||
///
|
||||
/// Используйте `@instance()` для методов или классов в DI-модуле,
|
||||
/// чтобы указать, что контейнер внедрения зависимостей должен создавать
|
||||
/// новый объект при каждом обращении к зависимости (то есть, не синглтон).
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @instance()
|
||||
/// Foo foo() => Foo();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Foo>().toInstance(() => foo());
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class instance {
|
||||
const instance();
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation for marking Dart classes or libraries as modules.
|
||||
///
|
||||
/// Use the `@module()` annotation on abstract classes (or on a library)
|
||||
/// to indicate that the class represents a DI (Dependency Injection) module.
|
||||
/// This is commonly used in code generation tools to automatically register
|
||||
/// and configure dependencies defined within the module.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// // Dependency definitions go here.
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Generates code like:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// // Dependency registration...
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для пометки классов или библиотек Dart как модуля.
|
||||
///
|
||||
/// Используйте `@module()` для абстрактных классов (или библиотек), чтобы
|
||||
/// показать, что класс реализует DI-модуль (Dependency Injection).
|
||||
/// Обычно используется генераторами кода для автоматической регистрации
|
||||
/// и конфигурирования зависимостей, определённых в модуле.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// // Определения зависимостей
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// // Регистрация зависимостей...
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class module {
|
||||
/// Creates a [module] annotation.
|
||||
const module();
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to assign a name or identifier to a class, method, or other element.
|
||||
///
|
||||
/// The `@named('value')` annotation allows you to specify a string name
|
||||
/// for a dependency, factory, or injectable. This is useful for distinguishing
|
||||
/// between multiple registrations of the same type in dependency injection,
|
||||
/// code generation, and for providing human-readable metadata.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @named('dio')
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This will generate:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).withName('dio').singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для задания имени или идентификатора классу, методу или другому элементу.
|
||||
///
|
||||
/// Аннотация `@named('значение')` позволяет указать строковое имя для зависимости,
|
||||
/// фабрики или внедряемого значения. Это удобно для различения нескольких
|
||||
/// регистраций одного типа в DI, генерации кода.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @named('dio')
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).withName('dio').singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class named {
|
||||
/// EN: The assigned name or identifier for the element.
|
||||
///
|
||||
/// RU: Назначенное имя или идентификатор для элемента.
|
||||
final String value;
|
||||
|
||||
/// EN: Creates a [named] annotation with the given [value].
|
||||
///
|
||||
/// RU: Создаёт аннотацию [named] с заданным значением [value].
|
||||
const named(this.value);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to mark a method parameter for injection with run-time arguments.
|
||||
///
|
||||
/// Use the `@params()` annotation to specify that a particular parameter of a
|
||||
/// provider method should be assigned a value supplied at resolution time,
|
||||
/// rather than during static dependency graph creation. This is useful in DI
|
||||
/// when a dependency must receive dynamic data passed by the consumer
|
||||
/// (via `.withParams(...)` in the generated code).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @provide()
|
||||
/// String greet(@params() dynamic params) => 'Hello $params';
|
||||
/// ```
|
||||
///
|
||||
/// This will generate:
|
||||
/// ```dart
|
||||
/// bind<String>().toProvideWithParams((args) => greet(args));
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для пометки параметра метода, который будет внедряться со значением во время выполнения.
|
||||
///
|
||||
/// Используйте `@params()` чтобы указать, что конкретный параметр метода-провайдера
|
||||
/// должен получать значение, передаваемое в момент обращения к зависимости,
|
||||
/// а не на этапе построения графа зависимостей. Это полезно, если зависимость
|
||||
/// должна получать данные динамически от пользователя или другого процесса
|
||||
/// через `.withParams(...)` в сгенерированном коде.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @provide()
|
||||
/// String greet(@params() dynamic params) => 'Hello $params';
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерировано:
|
||||
/// ```dart
|
||||
/// bind<String>().toProvideWithParams((args) => greet(args));
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class params {
|
||||
const params();
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to declare a factory/provider method or class as a singleton.
|
||||
///
|
||||
/// Use the `@singleton()` annotation on methods in your DI module to specify
|
||||
/// that only one instance of the resulting object should be created and shared
|
||||
/// for all consumers. This is especially useful in dependency injection
|
||||
/// frameworks and service locators.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This generates the following code:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для объявления фабричного/провайдерного метода или класса синглтоном.
|
||||
///
|
||||
/// Используйте `@singleton()` для методов внутри DI-модуля, чтобы указать,
|
||||
/// что соответствующий объект (экземпляр класса) должен быть создан только один раз
|
||||
/// и использоваться всеми компонентами приложения (единый общий экземпляр).
|
||||
/// Это характерно для систем внедрения зависимостей и сервис-локаторов.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class provide {
|
||||
const provide();
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Annotation to specify a scope for dependency injection in CherryPick.
|
||||
/// Use this on an injected field to indicate from which scope
|
||||
/// the dependency must be resolved.
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// Аннотация для указания области внедрения (scope) в CherryPick.
|
||||
/// Используйте её на инъецируемом поле, чтобы определить из какой области
|
||||
/// должна быть получена зависимость.
|
||||
///
|
||||
/// Example / Пример:
|
||||
/// ```dart
|
||||
/// @inject()
|
||||
/// @scope('profile')
|
||||
/// late final ProfileManager profileManager;
|
||||
/// ```
|
||||
@experimental
|
||||
// ignore: camel_case_types
|
||||
final class scope {
|
||||
final String? name;
|
||||
const scope(this.name);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to declare a dependency as a singleton.
|
||||
///
|
||||
/// Use the `@singleton()` annotation on provider methods inside a module
|
||||
/// to indicate that only a single instance of this dependency should be
|
||||
/// created and shared throughout the application's lifecycle. This is
|
||||
/// typically used in dependency injection frameworks or service locators
|
||||
/// to guarantee a single shared instance.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This will generate code like:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для объявления зависимости как синглтона.
|
||||
///
|
||||
/// Используйте `@singleton()` для методов-провайдеров внутри модуля,
|
||||
/// чтобы указать, что соответствующий объект должен быть создан
|
||||
/// единожды и использоваться во всём приложении (общий синглтон).
|
||||
/// Это характерно для систем внедрения зависимостей и сервис-локаторов,
|
||||
/// чтобы гарантировать один общий экземпляр.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class singleton {
|
||||
/// Creates a [singleton] annotation.
|
||||
const singleton();
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
name: cherrypick_annotations
|
||||
description: |
|
||||
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
|
||||
version: 1.1.0-dev.1
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
meta: ^1.15.0
|
||||
# path: ^1.8.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
test: ^1.25.8
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('A group of tests', () {
|
||||
setUp(() {
|
||||
// Additional setup goes here.
|
||||
});
|
||||
|
||||
test('First Test', () {
|
||||
expect(1, 1);
|
||||
});
|
||||
});
|
||||
}
|
||||
32
cherrypick_flutter/.gitignore
vendored
32
cherrypick_flutter/.gitignore
vendored
@@ -1,32 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
build/
|
||||
|
||||
|
||||
pubspec_overrides.yaml
|
||||
@@ -1,10 +0,0 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "4cf269e36de2573851eaef3c763994f8f9be494d"
|
||||
channel: "stable"
|
||||
|
||||
project_type: package
|
||||
@@ -1,34 +0,0 @@
|
||||
## 1.1.2-dev.1
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.2-dev.0
|
||||
|
||||
- **FIX**: fix warning.
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 1.1.1-dev.1
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
## 1.1.1-dev.0
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- **FIX**: update description.
|
||||
- **FIX**: update gitignore.
|
||||
- **FEAT**: modify api in CherryPickProvider.
|
||||
|
||||
## 1.0.1
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 0.0.1
|
||||
|
||||
* TODO: Describe initial release.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,97 +0,0 @@
|
||||
# CherryPick Flutter
|
||||
|
||||
`cherrypick_flutter` offers a Flutter integration to access and manage dependency injection scopes using the `CherryPickProvider`. This setup facilitates accessing the root scope directly from the widget tree, providing a straightforward mechanism for dependences management within Flutter applications.
|
||||
|
||||
## Installation
|
||||
|
||||
Add `cherrypick_flutter` to your `pubspec.yaml`:
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick_flutter: ^1.0.0
|
||||
```
|
||||
|
||||
Run `flutter pub get` to install the package dependencies.
|
||||
|
||||
## Usage
|
||||
|
||||
### Importing the Package
|
||||
|
||||
To begin using `cherrypick_flutter`, import it within your Dart file:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_flutter/cherrypick_flutter.dart';
|
||||
```
|
||||
|
||||
### Providing State with `CherryPickProvider`
|
||||
|
||||
Use `CherryPickProvider` to encase the widget tree section that requires access to the root or specific subscopes:
|
||||
|
||||
```dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cherrypick_flutter/cherrypick_flutter.dart';
|
||||
|
||||
void main() {
|
||||
runApp(
|
||||
CherryPickProvider(
|
||||
child: MyApp(),
|
||||
),
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Note: The current implementation of `CherryPickProvider` does not directly pass a `rootScope`. Instead, it utilizes its methods to open root and sub-scopes internally.
|
||||
|
||||
### Accessing State
|
||||
|
||||
Access the state provided by `CherryPickProvider` within widget `build` methods using the `of` method:
|
||||
|
||||
```dart
|
||||
class MyWidget extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final CherryPickProvider cherryPick = CherryPickProvider.of(context);
|
||||
final rootScope = cherryPick.openRootScope();
|
||||
|
||||
// Use the rootScope or open a subScope as needed
|
||||
final subScope = cherryPick.openSubScope(scopeName: "exampleScope");
|
||||
|
||||
return Text('Scope accessed!');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Updating State
|
||||
|
||||
The `CherryPickProvider` setup internally manages state updates. Ensure the `updateShouldNotify` method accurately reflects when the dependents should receive updates. In the provided implementation, it currently does not notify updates automatically.
|
||||
|
||||
## Example
|
||||
|
||||
Here is an example illustrating how to implement and utilize `CherryPickProvider` within a Flutter application:
|
||||
|
||||
```dart
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final rootScope = CherryPickProvider.of(context).openRootScope();
|
||||
|
||||
return MaterialApp.router(
|
||||
routerDelegate: rootScope.resolve<AppRouter>().delegate(),
|
||||
routeInformationParser:
|
||||
rootScope.resolve<AppRouter>().defaultRouteParser(),
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this example, `CherryPickProvider` accesses and resolves dependencies using root scope and potentially sub-scopes configured by the application.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions to improve this library are welcome. Feel free to open issues and submit pull requests on the repository.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the Apache License 2.0. A copy of the license can be obtained at [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
@@ -1,4 +0,0 @@
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
# Additional information about this file can be found at
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
@@ -1,15 +0,0 @@
|
||||
library;
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
export 'src/cherrypick_provider.dart';
|
||||
@@ -1,44 +0,0 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
///
|
||||
/// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
/// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
/// you may not use this file except in compliance with the License.
|
||||
/// You may obtain a copy of the License at
|
||||
/// http://www.apache.org/licenses/LICENSE-2.0
|
||||
/// Unless required by applicable law or agreed to in writing, software
|
||||
/// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
/// See the License for the specific language governing permissions and
|
||||
/// limitations under the License.
|
||||
///
|
||||
|
||||
final class CherryPickProvider extends InheritedWidget {
|
||||
Scope openRootScope() => CherryPick.openRootScope();
|
||||
|
||||
Scope openSubScope({String scopeName = '', String separator = '.'}) =>
|
||||
CherryPick.openScope(scopeName: scopeName, separator: separator);
|
||||
|
||||
// Constructor for CherryPickProvider. Initializes with a required rootScope and child widget.
|
||||
const CherryPickProvider({
|
||||
super.key,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
// Method to access the nearest CherryPickProvider instance from the context
|
||||
static CherryPickProvider of(BuildContext context) {
|
||||
// Looks up the widget tree for an instance of CherryPickProvider
|
||||
final CherryPickProvider? result =
|
||||
context.dependOnInheritedWidgetOfExactType<CherryPickProvider>();
|
||||
// Assert to ensure a CherryPickProvider is present in the context
|
||||
assert(result != null, 'No CherryPickProvider found in context');
|
||||
return result!;
|
||||
}
|
||||
|
||||
// Determines whether the widget should notify dependents when it changes
|
||||
@override
|
||||
bool updateShouldNotify(CherryPickProvider oldWidget) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
name: cherrypick_flutter
|
||||
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
|
||||
version: 1.1.2-dev.1
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
flutter: ">=3.24.0"
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
cherrypick: ^2.2.0-dev.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^5.0.0
|
||||
test: ^1.25.7
|
||||
melos: ^6.3.2
|
||||
|
||||
# For information on the generic Dart part of this file, see the
|
||||
# following page: https://dart.dev/tools/pub/pubspec
|
||||
|
||||
# The following section is specific to Flutter packages.
|
||||
flutter:
|
||||
|
||||
# To add assets to your package, add an assets section, like this:
|
||||
# assets:
|
||||
# - images/a_dot_burr.jpeg
|
||||
# - images/a_dot_ham.jpeg
|
||||
#
|
||||
# For details regarding assets in packages, see
|
||||
# https://flutter.dev/to/asset-from-package
|
||||
#
|
||||
# An image asset can refer to one or more resolution-specific "variants", see
|
||||
# https://flutter.dev/to/resolution-aware-images
|
||||
|
||||
# To add custom fonts to your package, add a fonts section here,
|
||||
# in this "flutter" section. Each entry in this list should have a
|
||||
# "family" key with the font family name, and a "fonts" key with a
|
||||
# list giving the asset and other descriptors for the font. For
|
||||
# example:
|
||||
# fonts:
|
||||
# - family: Schyler
|
||||
# fonts:
|
||||
# - asset: fonts/Schyler-Regular.ttf
|
||||
# - asset: fonts/Schyler-Italic.ttf
|
||||
# style: italic
|
||||
# - family: Trajan Pro
|
||||
# fonts:
|
||||
# - asset: fonts/TrajanPro.ttf
|
||||
# - asset: fonts/TrajanPro_Bold.ttf
|
||||
# weight: 700
|
||||
#
|
||||
# For details regarding fonts in packages, see
|
||||
# https://flutter.dev/to/font-from-package
|
||||
@@ -1,7 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('adds one to input values', () {
|
||||
expect(1, 1);
|
||||
});
|
||||
}
|
||||
28
cherrypick_generator/.gitignore
vendored
28
cherrypick_generator/.gitignore
vendored
@@ -1,28 +0,0 @@
|
||||
# See https://www.dartlang.org/guides/libraries/private-files
|
||||
|
||||
# Files and directories created by pub
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
||||
# If you're building an application, you may want to check-in your pubspec.lock
|
||||
pubspec.lock
|
||||
|
||||
# Directory created by dartdoc
|
||||
# If you don't generate documentation locally you can remove this line.
|
||||
doc/api/
|
||||
|
||||
# Avoid committing generated Javascript files:
|
||||
*.dart.js
|
||||
*.info.json # Produced by the --dump-info flag.
|
||||
*.js # When generated by dart2js. Don't specify *.js if your
|
||||
# project includes source files written in JavaScript.
|
||||
*.js_
|
||||
*.js.deps
|
||||
*.js.map
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
|
||||
melos_cherrypick_generator.iml
|
||||
|
||||
**/*.mocks.dart
|
||||
@@ -1,34 +0,0 @@
|
||||
## 1.1.0-dev.4
|
||||
|
||||
- **FIX**: fixed warnings.
|
||||
|
||||
## 1.1.0-dev.3
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
## 1.1.0-dev.2
|
||||
|
||||
- **FIX**: update instance generator code.
|
||||
|
||||
## 1.1.0-dev.1
|
||||
|
||||
- **FIX**: optimize code.
|
||||
|
||||
## 1.1.0-dev.0
|
||||
|
||||
- **FIX**: fix warning conflict with names.
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: fix module generator.
|
||||
- **FIX**: fix generator for singletone annotation.
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement async mode for instance/provide annotations.
|
||||
- **FEAT**: generate instance async code.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement named dependency.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- Initial version.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,203 +0,0 @@
|
||||
# Cherrypick Generator
|
||||
|
||||
**Cherrypick Generator** is a Dart code generation library for automating dependency injection (DI) boilerplate. It processes classes and fields annotated with [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations) and generates registration code for services, modules, and field injection for classes marked as `@injectable`. It supports advanced DI features such as scopes, named bindings, parameters, and asynchronous dependencies.
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **Automatic Field Injection:**
|
||||
Detects classes annotated with `@injectable()`, and generates mixins to inject all fields annotated with `@inject()`, supporting scope and named qualifiers.
|
||||
|
||||
- **Module and Service Registration:**
|
||||
For classes annotated with `@module()`, generates service registration code for methods using annotations such as `@provide`, `@instance`, `@singleton`, `@named`, and `@params`.
|
||||
|
||||
- **Scope & Named Qualifier Support:**
|
||||
Supports advanced DI features:
|
||||
• Field-level scoping with `@scope('scopename')`
|
||||
• Named dependencies via `@named('value')`
|
||||
|
||||
- **Synchronous & Asynchronous Support:**
|
||||
Handles both synchronous and asynchronous services (including `Future<T>`) for both field injection and module registration.
|
||||
|
||||
- **Parameters and Runtime Arguments:**
|
||||
Recognizes and wires both injected dependencies and runtime parameters using `@params`.
|
||||
|
||||
- **Error Handling:**
|
||||
Validates annotations at generation time. Provides helpful errors for incorrect usage (e.g., using `@injectable` on non-class elements).
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Annotate your code
|
||||
|
||||
Use annotations from [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations):
|
||||
|
||||
- `@injectable()` — on classes to enable field injection
|
||||
- `@inject()` — on fields to specify they should be injected
|
||||
- `@scope()`, `@named()` — on fields or parameters for advanced wiring
|
||||
- `@module()` — on classes to mark as DI modules
|
||||
- `@provide`, `@instance`, `@singleton`, `@params` — on methods and parameters for module-based DI
|
||||
|
||||
### 2. Run the generator
|
||||
|
||||
Use `build_runner` to process your code and generate `.module.cherrypick.g.dart` and `.inject.cherrypick.g.dart` files.
|
||||
|
||||
### 3. Use the output in your application
|
||||
|
||||
- For modules: Register DI providers using the generated `$YourModule` class.
|
||||
- For services: Enable field injection on classes using the generated mixin.
|
||||
|
||||
---
|
||||
|
||||
## Field Injection Example
|
||||
|
||||
Given the following:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@injectable()
|
||||
class MyWidget with _$MyWidget {
|
||||
@inject()
|
||||
late final AuthService auth;
|
||||
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager manager;
|
||||
|
||||
@inject()
|
||||
@named('special')
|
||||
late final ApiClient specialApi;
|
||||
}
|
||||
```
|
||||
|
||||
**The generator will output (simplified):**
|
||||
```dart
|
||||
mixin _$MyWidget {
|
||||
void _inject(MyWidget instance) {
|
||||
instance.auth = CherryPick.openRootScope().resolve<AuthService>();
|
||||
instance.manager = CherryPick.openScope(scopeName: 'profile').resolve<ProfileManager>();
|
||||
instance.specialApi = CherryPick.openRootScope().resolve<ApiClient>(named: 'special');
|
||||
}
|
||||
}
|
||||
```
|
||||
You can then mix this into your widget to enable automatic DI at runtime.
|
||||
|
||||
---
|
||||
|
||||
## Module Registration Example
|
||||
|
||||
Given:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@module()
|
||||
class MyModule {
|
||||
@singleton
|
||||
@instance
|
||||
AuthService provideAuth(Api api);
|
||||
|
||||
@provide
|
||||
@named('logging')
|
||||
Future<Logger> provideLogger(@params Map<String, dynamic> args);
|
||||
}
|
||||
```
|
||||
|
||||
**The generator will output (simplified):**
|
||||
```dart
|
||||
final class $MyModule extends MyModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<AuthService>()
|
||||
.toInstance(provideAuth(currentScope.resolve<Api>()))
|
||||
.singleton();
|
||||
|
||||
bind<Logger>()
|
||||
.toProvideAsyncWithParams((args) => provideLogger(args))
|
||||
.withName('logging');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Points
|
||||
|
||||
- **Rich Annotation Support:**
|
||||
Mix and match field, parameter, and method annotations for maximum flexibility.
|
||||
- **Scope and Named Resolution:**
|
||||
Use `@scope('...')` and `@named('...')` to precisely control where and how dependencies are wired.
|
||||
- **Async/Synchronous:**
|
||||
The generator distinguishes between sync (`resolve<T>`) and async (`resolveAsync<T>`) dependencies.
|
||||
- **Automatic Mixins:**
|
||||
For classes with `@injectable()`, a mixin is generated that injects all relevant fields (using constructor or setter).
|
||||
- **Comprehensive Error Checking:**
|
||||
Misapplied annotations (e.g., `@injectable()` on non-class) produce clear build-time errors.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Add dependencies**
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick_annotations: ^latest
|
||||
|
||||
dev_dependencies:
|
||||
cherrypick_generator: ^latest
|
||||
build_runner: ^2.1.0
|
||||
```
|
||||
|
||||
2. **Annotate your classes and modules as above**
|
||||
|
||||
3. **Run the generator**
|
||||
|
||||
```shell
|
||||
dart run build_runner build
|
||||
# or, if using Flutter:
|
||||
flutter pub run build_runner build
|
||||
```
|
||||
|
||||
4. **Use generated code**
|
||||
|
||||
- Import the generated `.inject.cherrypick.g.dart` or `.cherrypick.g.dart` files where needed
|
||||
|
||||
---
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
- **Combining Modules and Field Injection:**
|
||||
It's possible to mix both style of DI — modules for binding, and field injection for consuming services.
|
||||
- **Parameter and Named Injection:**
|
||||
Use `@named` on both provider and parameter for named registration and lookup; use `@params` to pass runtime arguments.
|
||||
- **Async Factories:**
|
||||
Methods returning Future<T> generate async bindings and async field resolution logic.
|
||||
|
||||
---
|
||||
|
||||
## Developer Notes
|
||||
|
||||
- The generator relies on the Dart analyzer, `source_gen`, and `build` packages.
|
||||
- All classes and methods are parsed for annotations.
|
||||
- Improper annotation usage will result in generator errors.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
```
|
||||
Licensed under the Apache License, Version 2.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Contribution
|
||||
|
||||
Pull requests and issues are welcome! Please open GitHub issues or submit improvements.
|
||||
|
||||
---
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
|
||||
analyzer:
|
||||
errors:
|
||||
deprecated_member_use: ignore
|
||||
@@ -1,27 +0,0 @@
|
||||
builders:
|
||||
module_generator:
|
||||
import: "package:cherrypick_generator/module_generator.dart"
|
||||
builder_factories: ["moduleBuilder"]
|
||||
build_extensions: {".dart": [".cherrypick.g.dart"]}
|
||||
auto_apply: dependents
|
||||
required_inputs: ["lib/**"]
|
||||
runs_before: []
|
||||
build_to: source
|
||||
inject_generator:
|
||||
import: "package:cherrypick_generator/inject_generator.dart"
|
||||
builder_factories: ["injectBuilder"]
|
||||
build_extensions: {".dart": [".cherrypick.g.dart"]}
|
||||
auto_apply: dependents
|
||||
required_inputs: ["lib/**"]
|
||||
runs_before: []
|
||||
build_to: source
|
||||
|
||||
targets:
|
||||
$default:
|
||||
builders:
|
||||
cherrypick_generator|module_generator:
|
||||
generate_for:
|
||||
- lib/**.dart
|
||||
cherrypick_generator|inject_generator:
|
||||
generate_for:
|
||||
- lib/**.dart
|
||||
@@ -1,17 +0,0 @@
|
||||
library;
|
||||
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
export 'module_generator.dart';
|
||||
export 'inject_generator.dart';
|
||||
@@ -1,186 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:analyzer/dart/constant/value.dart';
|
||||
import 'package:analyzer/dart/element/type.dart';
|
||||
import 'package:build/build.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||
|
||||
/// InjectGenerator generates a mixin for a class marked with @injectable()
|
||||
/// and injects all fields annotated with @inject(), using CherryPick DI.
|
||||
///
|
||||
/// For Future<T> fields it calls .resolveAsync<T>(),
|
||||
/// otherwise .resolve<T>() is used. Scope and named qualifiers are supported.
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// InjectGenerator генерирует миксин для класса с аннотацией @injectable()
|
||||
/// и внедряет все поля, помеченные @inject(), используя DI-фреймворк CherryPick.
|
||||
///
|
||||
/// Для Future<T> полей вызывается .resolveAsync<T>(),
|
||||
/// для остальных — .resolve<T>(). Поддерживаются scope и named qualifier.
|
||||
///
|
||||
class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
const InjectGenerator();
|
||||
|
||||
/// The main entry point for code generation.
|
||||
///
|
||||
/// Checks class validity, collects injectable fields, and produces injection code.
|
||||
///
|
||||
/// Основная точка входа генератора. Проверяет класс, собирает инъектируемые поля и создает код внедрения зависимостей.
|
||||
@override
|
||||
FutureOr<String> generateForAnnotatedElement(
|
||||
Element element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
if (element is! ClassElement) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@injectable() can only be applied to classes.',
|
||||
element: element,
|
||||
);
|
||||
}
|
||||
|
||||
final classElement = element;
|
||||
final className = classElement.name;
|
||||
final mixinName = '_\$$className';
|
||||
|
||||
final buffer = StringBuffer()
|
||||
..writeln('mixin $mixinName {')
|
||||
..writeln(' void _inject($className instance) {');
|
||||
|
||||
// Collect and process all @inject fields.
|
||||
// Собираем и обрабатываем все поля с @inject.
|
||||
final injectFields =
|
||||
classElement.fields.where(_isInjectField).map(_parseInjectField);
|
||||
|
||||
for (final parsedField in injectFields) {
|
||||
buffer.writeln(_generateInjectionLine(parsedField));
|
||||
}
|
||||
|
||||
buffer
|
||||
..writeln(' }')
|
||||
..writeln('}');
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/// Checks if a field has the @inject annotation.
|
||||
///
|
||||
/// Проверяет, отмечено ли поле аннотацией @inject.
|
||||
static bool _isInjectField(FieldElement field) {
|
||||
return field.metadata.any(
|
||||
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses the field for scope/named qualifiers and determines its type.
|
||||
/// Returns a [_ParsedInjectField] describing injection information.
|
||||
///
|
||||
/// Разбирает поле на наличие модификаторов scope/named и выясняет его тип.
|
||||
/// Возвращает [_ParsedInjectField] с информацией о внедрении.
|
||||
static _ParsedInjectField _parseInjectField(FieldElement field) {
|
||||
String? scopeName;
|
||||
String? namedValue;
|
||||
|
||||
for (final meta in field.metadata) {
|
||||
final DartObject? obj = meta.computeConstantValue();
|
||||
final type = obj?.type?.getDisplayString();
|
||||
if (type == 'scope') {
|
||||
scopeName = obj?.getField('name')?.toStringValue();
|
||||
} else if (type == 'named') {
|
||||
namedValue = obj?.getField('value')?.toStringValue();
|
||||
}
|
||||
}
|
||||
|
||||
final DartType dartType = field.type;
|
||||
String coreTypeName;
|
||||
bool isFuture;
|
||||
|
||||
if (dartType.isDartAsyncFuture) {
|
||||
final ParameterizedType paramType = dartType as ParameterizedType;
|
||||
coreTypeName = paramType.typeArguments.first.getDisplayString();
|
||||
isFuture = true;
|
||||
} else {
|
||||
coreTypeName = dartType.getDisplayString();
|
||||
isFuture = false;
|
||||
}
|
||||
|
||||
return _ParsedInjectField(
|
||||
fieldName: field.name,
|
||||
coreType: coreTypeName,
|
||||
isFuture: isFuture,
|
||||
scopeName: scopeName,
|
||||
namedValue: namedValue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Generates a line of code that performs the dependency injection for a field.
|
||||
/// Handles resolve/resolveAsync, scoping, and named qualifiers.
|
||||
///
|
||||
/// Генерирует строку кода, которая внедряет зависимость для поля.
|
||||
/// Учитывает resolve/resolveAsync, scoping и named qualifier.
|
||||
String _generateInjectionLine(_ParsedInjectField field) {
|
||||
final methodName = field.isFuture
|
||||
? 'resolveAsync<${field.coreType}>'
|
||||
: 'resolve<${field.coreType}>';
|
||||
final openCall = (field.scopeName != null && field.scopeName!.isNotEmpty)
|
||||
? "CherryPick.openScope(scopeName: '${field.scopeName}')"
|
||||
: "CherryPick.openRootScope()";
|
||||
final params = (field.namedValue != null && field.namedValue!.isNotEmpty)
|
||||
? "(named: '${field.namedValue}')"
|
||||
: '()';
|
||||
|
||||
return " instance.${field.fieldName} = $openCall.$methodName$params;";
|
||||
}
|
||||
}
|
||||
|
||||
/// Data structure representing all information required to generate
|
||||
/// injection code for a field.
|
||||
///
|
||||
/// Структура данных, содержащая всю информацию,
|
||||
/// необходимую для генерации кода внедрения для поля.
|
||||
class _ParsedInjectField {
|
||||
/// The name of the field / Имя поля.
|
||||
final String fieldName;
|
||||
|
||||
/// The base type name (T or Future<T>) / Базовый тип (T или тип из Future<T>).
|
||||
final String coreType;
|
||||
|
||||
/// True if the field type is Future<T>; false otherwise
|
||||
/// Истина, если поле — Future<T>, иначе — ложь.
|
||||
final bool isFuture;
|
||||
|
||||
/// Optional scope annotation argument / Опциональное имя scope.
|
||||
final String? scopeName;
|
||||
|
||||
/// Optional named annotation argument / Опциональное имя named.
|
||||
final String? namedValue;
|
||||
|
||||
_ParsedInjectField({
|
||||
required this.fieldName,
|
||||
required this.coreType,
|
||||
required this.isFuture,
|
||||
this.scopeName,
|
||||
this.namedValue,
|
||||
});
|
||||
}
|
||||
|
||||
/// Builder factory. Used by build_runner.
|
||||
///
|
||||
/// Фабрика билдера. Используется build_runner.
|
||||
Builder injectBuilder(BuilderOptions options) =>
|
||||
PartBuilder([InjectGenerator()], '.inject.cherrypick.g.dart');
|
||||
@@ -1,93 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:build/build.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||
|
||||
import 'src/generated_class.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// ModuleGenerator for code generation of dependency-injected modules.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// This generator scans for Dart classes annotated with `@module()` and
|
||||
/// automatically generates boilerplate code for dependency injection
|
||||
/// (DI) based on the public methods in those classes. Each method can be
|
||||
/// annotated to describe how an object should be provided to the DI container.
|
||||
/// The generated code registers those methods as bindings. This automates the
|
||||
/// creation of factories, singletons, and named instances, reducing repetitive
|
||||
/// manual code.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генератор зависимостей для DI-контейнера на основе аннотаций.
|
||||
/// Данный генератор автоматически создаёт код для внедрения зависимостей (DI)
|
||||
/// на основе аннотаций в вашем исходном коде. Когда вы отмечаете класс
|
||||
/// аннотацией `@module()`, этот генератор обработает все его публичные методы
|
||||
/// и автоматически сгенерирует класс с биндингами (регистрациями зависимостей)
|
||||
/// для DI-контейнера. Это избавляет от написания однообразного шаблонного кода.
|
||||
/// ---------------------------------------------------------------------------
|
||||
|
||||
class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
|
||||
/// -------------------------------------------------------------------------
|
||||
/// ENGLISH
|
||||
/// Generates the Dart source for a class marked with the `@module()` annotation.
|
||||
/// - [element]: the original Dart class element.
|
||||
/// - [annotation]: the annotation parameters (not usually used here).
|
||||
/// - [buildStep]: the current build step info.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генерирует исходный код для класса-модуля с аннотацией `@module()`.
|
||||
/// [element] — исходный класс, помеченный аннотацией.
|
||||
/// [annotation] — значения параметров аннотации.
|
||||
/// [buildStep] — информация о текущем шаге генерации.
|
||||
/// -------------------------------------------------------------------------
|
||||
@override
|
||||
String generateForAnnotatedElement(
|
||||
Element element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
// Only classes are supported for @module() annotation
|
||||
// Обрабатываются только классы (другие элементы — ошибка)
|
||||
if (element is! ClassElement) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@module() can only be applied to classes. / @module() может быть применён только к классам.',
|
||||
element: element,
|
||||
);
|
||||
}
|
||||
|
||||
final classElement = element;
|
||||
|
||||
// Build a representation of the generated bindings based on class methods /
|
||||
// Создаёт объект, описывающий, какие биндинги нужно сгенерировать на основании методов класса
|
||||
final generatedClass = GeneratedClass.fromClassElement(classElement);
|
||||
|
||||
// Generate the resulting Dart code / Генерирует итоговый Dart-код
|
||||
return generatedClass.generate();
|
||||
}
|
||||
}
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// ENGLISH
|
||||
/// Entry point for build_runner. Returns a Builder used to generate code for
|
||||
/// every file with a @module() annotation.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Точка входа для генератора build_runner.
|
||||
/// Возвращает Builder, используемый build_runner для генерации кода для всех
|
||||
/// файлов, где встречается @module().
|
||||
/// ---------------------------------------------------------------------------
|
||||
Builder moduleBuilder(BuilderOptions options) =>
|
||||
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart');
|
||||
@@ -1,75 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// BindParameterSpec - describes a single method parameter and how to resolve it.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Describes a single parameter for a provider/binding method in the DI system.
|
||||
/// Stores the parameter type, its optional `@named` key for named resolution,
|
||||
/// and whether it is a runtime "params" argument. Used to generate code that
|
||||
/// resolves dependencies from the DI scope:
|
||||
/// - If the parameter is a dependency type (e.g. SomeDep), emits:
|
||||
/// currentScope.resolve<SomeDep>()
|
||||
/// - If the parameter is named, emits:
|
||||
/// currentScope.resolve<SomeDep>(named: 'yourName')
|
||||
/// - If it's a runtime parameter (e.g. via @params()), emits:
|
||||
/// args
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Описывает один параметр метода в DI, и его способ разрешения из контейнера.
|
||||
/// Сохраняет имя типа, дополнительное имя (если параметр аннотирован через @named),
|
||||
/// и признак runtime-параметра (@params).
|
||||
/// Для обычной зависимости типа (например, SomeDep) генерирует строку вида:
|
||||
/// currentScope.resolve<SomeDep>()
|
||||
/// Для зависимости с именем:
|
||||
/// currentScope.resolve<SomeDep>(named: 'имя')
|
||||
/// Для runtime-параметра:
|
||||
/// args
|
||||
/// ----------------------------------------------------------------------------
|
||||
class BindParameterSpec {
|
||||
/// Type name of the parameter (e.g. SomeService)
|
||||
/// Имя типа параметра (например, SomeService)
|
||||
final String typeName;
|
||||
|
||||
/// Optional name for named resolution (from @named)
|
||||
/// Необязательное имя для разрешения по имени (если аннотировано через @named)
|
||||
final String? named;
|
||||
|
||||
/// True if this parameter uses @params and should be provided from runtime args
|
||||
/// Признак, что параметр — runtime (через @params)
|
||||
final bool isParams;
|
||||
|
||||
BindParameterSpec(this.typeName, this.named, {this.isParams = false});
|
||||
|
||||
/// --------------------------------------------------------------------------
|
||||
/// generateArg
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Generates Dart code for resolving the dependency from the DI scope,
|
||||
/// considering type, named, and param-argument.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генерирует строку для получения зависимости из DI scope (с учётом имени
|
||||
/// и типа параметра или runtime-режима @params).
|
||||
/// --------------------------------------------------------------------------
|
||||
String generateArg([String paramsVar = 'args']) {
|
||||
if (isParams) {
|
||||
return paramsVar;
|
||||
}
|
||||
if (named != null) {
|
||||
return "currentScope.resolve<$typeName>(named: '$named')";
|
||||
}
|
||||
return "currentScope.resolve<$typeName>()";
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
|
||||
import 'bind_parameters_spec.dart';
|
||||
import 'metadata_utils.dart';
|
||||
|
||||
enum BindingType {
|
||||
instance,
|
||||
provide;
|
||||
}
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// BindSpec -- describes a binding specification generated for a dependency.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Represents all the data necessary to generate a DI binding for a single
|
||||
/// method in a module class. Each BindSpec corresponds to one public method
|
||||
/// and contains information about its type, provider method, lifecycle (singleton),
|
||||
/// parameters (with their annotations), binding strategy (instance/provide),
|
||||
/// asynchronous mode, and named keys. It is responsible for generating the
|
||||
/// correct Dart code to register this binding with the DI container, in both
|
||||
/// sync and async cases, with and without named or runtime arguments.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Описывает параметры для создания одного биндинга зависимости (binding spec).
|
||||
/// Каждый биндинг соответствует одному публичному методу класса-модуля и
|
||||
/// содержит всю информацию для генерации кода регистрации этого биндинга в
|
||||
/// DI-контейнере: тип возвращаемой зависимости, имя метода, параметры, аннотации
|
||||
/// (@singleton, @named, @instance, @provide), асинхронность, признак runtime
|
||||
/// аргументов и др. Генерирует правильный Dart-код для регистрации биндера.
|
||||
/// ---------------------------------------------------------------------------
|
||||
class BindSpec {
|
||||
/// The type this binding provides (e.g. SomeService)
|
||||
/// Тип, который предоставляет биндинг (например, SomeService)
|
||||
final String returnType;
|
||||
|
||||
/// Method name that implements the binding
|
||||
/// Имя метода, который реализует биндинг
|
||||
final String methodName;
|
||||
|
||||
/// Optional name for named dependency (from @named)
|
||||
/// Необязательное имя, для именованной зависимости (используется с @named)
|
||||
final String? named;
|
||||
|
||||
/// Whether the dependency is a singleton (@singleton annotation)
|
||||
/// Является ли зависимость синглтоном (имеется ли аннотация @singleton)
|
||||
final bool isSingleton;
|
||||
|
||||
/// List of method parameters to inject dependencies with
|
||||
/// Список параметров, которые требуются методу для внедрения зависимостей
|
||||
final List<BindParameterSpec> parameters;
|
||||
|
||||
/// Binding type: 'instance' or 'provide' (@instance or @provide)
|
||||
final BindingType bindingType; // 'instance' | 'provide'
|
||||
|
||||
/// True if the method is asynchronous and uses instance binding (Future)
|
||||
final bool isAsyncInstance;
|
||||
|
||||
/// True if the method is asynchronous and uses provide binding (Future)
|
||||
final bool isAsyncProvide;
|
||||
|
||||
/// True if the binding method accepts runtime "params" argument (@params)
|
||||
final bool hasParams;
|
||||
|
||||
BindSpec({
|
||||
required this.returnType,
|
||||
required this.methodName,
|
||||
required this.isSingleton,
|
||||
required this.parameters,
|
||||
this.named,
|
||||
required this.bindingType,
|
||||
required this.isAsyncInstance,
|
||||
required this.isAsyncProvide,
|
||||
required this.hasParams,
|
||||
});
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// generateBind
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Generates a line of Dart code registering the binding with the DI framework.
|
||||
/// Produces something like:
|
||||
/// bind<Type>().toProvide(() => method(args)).withName('name').singleton();
|
||||
/// Indent parameter allows formatted multiline output.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Формирует dart-код для биндинга, например:
|
||||
/// bind<Type>().toProvide(() => method(args)).withName('name').singleton();
|
||||
/// Параметр [indent] задаёт отступ для красивого форматирования кода.
|
||||
/// -------------------------------------------------------------------------
|
||||
String generateBind(int indent) {
|
||||
final indentStr = ' ' * indent;
|
||||
final provide = _generateProvideClause(indent);
|
||||
final postfix = _generatePostfix();
|
||||
return '$indentStr'
|
||||
'bind<$returnType>()'
|
||||
'$provide'
|
||||
'$postfix;';
|
||||
}
|
||||
|
||||
// Internal method: decides how the provide clause should be generated by param kind.
|
||||
String _generateProvideClause(int indent) {
|
||||
if (hasParams) return _generateWithParamsProvideClause(indent);
|
||||
return _generatePlainProvideClause(indent);
|
||||
}
|
||||
|
||||
/// EN / RU: Supports runtime parameters (@params).
|
||||
String _generateWithParamsProvideClause(int indent) {
|
||||
// Safe variable name for parameters.
|
||||
const paramVar = 'args';
|
||||
final fnArgs = parameters.map((p) => p.generateArg(paramVar)).join(', ');
|
||||
final multiLine = fnArgs.length > 60 || fnArgs.contains('\n');
|
||||
switch (bindingType) {
|
||||
case BindingType.instance:
|
||||
throw StateError(
|
||||
'Internal error: _generateWithParamsProvideClause called for @instance binding with @params.');
|
||||
//return isAsyncInstance
|
||||
// ? '.toInstanceAsync(($fnArgs) => $methodName($fnArgs))'
|
||||
// : '.toInstance(($fnArgs) => $methodName($fnArgs))';
|
||||
case BindingType.provide:
|
||||
if (isAsyncProvide) {
|
||||
return multiLine
|
||||
? '.toProvideAsyncWithParams(\n${' ' * (indent + 2)}($paramVar) => $methodName($fnArgs))'
|
||||
: '.toProvideAsyncWithParams(($paramVar) => $methodName($fnArgs))';
|
||||
} else {
|
||||
return multiLine
|
||||
? '.toProvideWithParams(\n${' ' * (indent + 2)}($paramVar) => $methodName($fnArgs))'
|
||||
: '.toProvideWithParams(($paramVar) => $methodName($fnArgs))';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// EN / RU: Supports only injected dependencies, not runtime (@params).
|
||||
String _generatePlainProvideClause(int indent) {
|
||||
final argsStr = parameters.map((p) => p.generateArg()).join(', ');
|
||||
final multiLine = argsStr.length > 60 || argsStr.contains('\n');
|
||||
switch (bindingType) {
|
||||
case BindingType.instance:
|
||||
return isAsyncInstance
|
||||
? '.toInstanceAsync($methodName($argsStr))'
|
||||
: '.toInstance($methodName($argsStr))';
|
||||
case BindingType.provide:
|
||||
if (isAsyncProvide) {
|
||||
return multiLine
|
||||
? '.toProvideAsync(\n${' ' * (indent + 2)}() => $methodName($argsStr))'
|
||||
: '.toProvideAsync(() => $methodName($argsStr))';
|
||||
} else {
|
||||
return multiLine
|
||||
? '.toProvide(\n${' ' * (indent + 2)}() => $methodName($argsStr))'
|
||||
: '.toProvide(() => $methodName($argsStr))';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// EN / RU: Adds .withName and .singleton if needed.
|
||||
String _generatePostfix() {
|
||||
final namePart = named != null ? ".withName('$named')" : '';
|
||||
final singletonPart = isSingleton ? '.singleton()' : '';
|
||||
return '$namePart$singletonPart';
|
||||
}
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// fromMethod
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Creates a BindSpec from a module class method by analyzing its return type,
|
||||
/// annotations, list of parameters (with their own annotations), and async-ness.
|
||||
/// Throws if a method does not have the required @instance() or @provide().
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Создаёт спецификацию биндинга (BindSpec) из метода класса-модуля, анализируя
|
||||
/// возвращаемый тип, аннотации, параметры (и их аннотации), а также факт
|
||||
/// асинхронности. Если нет @instance или @provide — кидает ошибку.
|
||||
/// -------------------------------------------------------------------------
|
||||
static BindSpec fromMethod(MethodElement method) {
|
||||
var returnType = method.returnType.getDisplayString();
|
||||
|
||||
final methodName = method.displayName;
|
||||
// Check for @singleton annotation.
|
||||
final isSingleton = MetadataUtils.anyMeta(method.metadata, 'singleton');
|
||||
|
||||
// Get @named value if present.
|
||||
final named = MetadataUtils.getNamedValue(method.metadata);
|
||||
|
||||
// Parse each method parameter.
|
||||
final params = <BindParameterSpec>[];
|
||||
bool hasParams = false;
|
||||
for (final p in method.parameters) {
|
||||
final typeStr = p.type.getDisplayString();
|
||||
final paramNamed = MetadataUtils.getNamedValue(p.metadata);
|
||||
final isParams = MetadataUtils.anyMeta(p.metadata, 'params');
|
||||
if (isParams) hasParams = true;
|
||||
params.add(BindParameterSpec(typeStr, paramNamed, isParams: isParams));
|
||||
}
|
||||
|
||||
// Determine bindingType: @instance or @provide.
|
||||
final hasInstance = MetadataUtils.anyMeta(method.metadata, 'instance');
|
||||
final hasProvide = MetadataUtils.anyMeta(method.metadata, 'provide');
|
||||
if (!hasInstance && !hasProvide) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'Method $methodName must be marked with @instance() or @provide().',
|
||||
element: method,
|
||||
);
|
||||
}
|
||||
final bindingType =
|
||||
hasInstance ? BindingType.instance : BindingType.provide;
|
||||
|
||||
// PROHIBIT @params with @instance bindings!
|
||||
if (bindingType == BindingType.instance && hasParams) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@params() (runtime arguments) cannot be used together with @instance() on method $methodName. '
|
||||
'Use @provide() instead if you want runtime arguments.',
|
||||
element: method,
|
||||
);
|
||||
}
|
||||
|
||||
// -- Extract inner type for Future<T> and set async flags.
|
||||
bool isAsyncInstance = false;
|
||||
bool isAsyncProvide = false;
|
||||
final futureInnerType = _extractFutureInnerType(returnType);
|
||||
if (futureInnerType != null) {
|
||||
returnType = futureInnerType;
|
||||
if (bindingType == BindingType.instance) isAsyncInstance = true;
|
||||
if (bindingType == BindingType.provide) isAsyncProvide = true;
|
||||
}
|
||||
|
||||
return BindSpec(
|
||||
returnType: returnType,
|
||||
methodName: methodName,
|
||||
isSingleton: isSingleton,
|
||||
named: named,
|
||||
parameters: params,
|
||||
bindingType: bindingType,
|
||||
isAsyncInstance: isAsyncInstance,
|
||||
isAsyncProvide: isAsyncProvide,
|
||||
hasParams: hasParams,
|
||||
);
|
||||
}
|
||||
|
||||
/// EN / RU: Extracts inner type from Future<T>, returns e.g. "T" or null.
|
||||
static String? _extractFutureInnerType(String typeName) {
|
||||
final match = RegExp(r'^Future<(.+)>$').firstMatch(typeName);
|
||||
return match?.group(1)?.trim();
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
|
||||
import 'bind_spec.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// GeneratedClass -- represents the result of processing a single module class.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Encapsulates all the information produced from analyzing a DI module class:
|
||||
/// - The original class name,
|
||||
/// - Its generated class name (e.g., `$SomeModule`),
|
||||
/// - The collection of bindings (BindSpec) for all implemented provider methods.
|
||||
///
|
||||
/// Also provides code generation functionality, allowing to generate the source
|
||||
/// code for the derived DI module class, including all binding registrations.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Описывает результат обработки одного класса-модуля DI:
|
||||
/// - Имя оригинального класса,
|
||||
/// - Имя генерируемого класса (например, `$SomeModule`),
|
||||
/// - Список всех бидингов (BindSpec) — по публичным методам модуля.
|
||||
///
|
||||
/// Также содержит функцию генерации исходного кода для этого класса и
|
||||
/// регистрации всех зависимостей через bind(...).
|
||||
/// ---------------------------------------------------------------------------
|
||||
class GeneratedClass {
|
||||
/// The name of the original module class.
|
||||
/// Имя исходного класса-модуля
|
||||
final String className;
|
||||
|
||||
/// The name of the generated class (e.g., $SomeModule).
|
||||
/// Имя генерируемого класса (например, $SomeModule)
|
||||
final String generatedClassName;
|
||||
|
||||
/// List of all discovered bindings for the class.
|
||||
/// Список всех обнаруженных биндингов
|
||||
final List<BindSpec> binds;
|
||||
|
||||
GeneratedClass(
|
||||
this.className,
|
||||
this.generatedClassName,
|
||||
this.binds,
|
||||
);
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// fromClassElement
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Static factory: creates a GeneratedClass from a Dart ClassElement (AST representation).
|
||||
/// Discovers all non-abstract methods, builds BindSpec for each, and computes the
|
||||
/// generated class name by prefixing `$`.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Строит объект класса по элементу AST (ClassElement): имя класса,
|
||||
/// сгенерированное имя, список BindSpec по всем не абстрактным методам.
|
||||
/// Имя ген-класса строится с префиксом `$`.
|
||||
/// -------------------------------------------------------------------------
|
||||
static GeneratedClass fromClassElement(ClassElement element) {
|
||||
final className = element.displayName;
|
||||
// Generated class name with '$' prefix (standard for generated Dart code).
|
||||
final generatedClassName = r'$' + className;
|
||||
// Collect bindings for all non-abstract methods.
|
||||
final binds = element.methods
|
||||
.where((m) => !m.isAbstract)
|
||||
.map(BindSpec.fromMethod)
|
||||
.toList();
|
||||
|
||||
return GeneratedClass(className, generatedClassName, binds);
|
||||
}
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// generate
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Generates Dart source code for the DI module class. The generated class
|
||||
/// inherits from the original, overrides the 'builder' method, and registers
|
||||
/// all bindings in the DI scope.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генерирует исходный Dart-код для класса-модуля DI.
|
||||
/// Новая версия класса наследует оригинальный, переопределяет builder(Scope),
|
||||
/// и регистрирует все зависимости через методы bind<Type>()...
|
||||
/// -------------------------------------------------------------------------
|
||||
String generate() {
|
||||
final buffer = StringBuffer();
|
||||
|
||||
buffer.writeln('final class $generatedClassName extends $className {');
|
||||
buffer.writeln(' @override');
|
||||
buffer.writeln(' void builder(Scope currentScope) {');
|
||||
|
||||
// For each binding, generate bind<Type>() code string.
|
||||
// Для каждого биндинга — генерируем строку bind<Type>()...
|
||||
for (final bind in binds) {
|
||||
buffer.writeln(bind.generateBind(4));
|
||||
}
|
||||
|
||||
buffer.writeln(' }');
|
||||
buffer.writeln('}');
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// MetadataUtils -- utilities for analyzing method and parameter annotations.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Provides static utility methods to analyze Dart annotations on methods or
|
||||
/// parameters. For instance, helps to find if an element is annotated with
|
||||
/// `@named()`, `@singleton()`, or other meta-annotations used in this DI framework.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Утилиты для разбора аннотаций методов и параметров.
|
||||
/// Позволяют находить наличие аннотаций, например, @named() и @singleton(),
|
||||
/// у методов и параметров. Используется для анализа исходного кода при генерации.
|
||||
/// ---------------------------------------------------------------------------
|
||||
class MetadataUtils {
|
||||
/// -------------------------------------------------------------------------
|
||||
/// anyMeta
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Checks if any annotation in the list has a type name that contains
|
||||
/// [typeName] (case insensitive).
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Проверяет: есть ли среди аннотаций метка, имя которой содержит [typeName]
|
||||
/// (регистр не учитывается).
|
||||
/// -------------------------------------------------------------------------
|
||||
static bool anyMeta(List<ElementAnnotation> meta, String typeName) {
|
||||
return meta.any((m) =>
|
||||
m
|
||||
.computeConstantValue()
|
||||
?.type
|
||||
?.getDisplayString()
|
||||
.toLowerCase()
|
||||
.contains(typeName.toLowerCase()) ??
|
||||
false);
|
||||
}
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// getNamedValue
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Retrieves the value from a `@named('value')` annotation if present.
|
||||
/// Returns the string value or null if not found.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Находит значение из аннотации @named('значение').
|
||||
/// Возвращает строку значения, если аннотация присутствует; иначе null.
|
||||
/// -------------------------------------------------------------------------
|
||||
static String? getNamedValue(List<ElementAnnotation> meta) {
|
||||
for (final m in meta) {
|
||||
final cv = m.computeConstantValue();
|
||||
|
||||
final typeStr = cv?.type?.getDisplayString().toLowerCase();
|
||||
|
||||
if (typeStr?.contains('named') ?? false) {
|
||||
return cv?.getField('value')?.toStringValue();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
name: cherrypick_generator
|
||||
description: |
|
||||
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
|
||||
|
||||
version: 1.1.0-dev.4
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
cherrypick_annotations: ^1.1.0-dev.1
|
||||
analyzer: ^7.0.0
|
||||
dart_style: ^3.0.1
|
||||
build: ^2.4.1
|
||||
build_runner: ^2.4.15
|
||||
source_gen: ^2.0.0
|
||||
collection: ^1.18.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
mockito: ^5.4.4
|
||||
test: ^1.25.8
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('A group of tests', () {
|
||||
setUp(() {
|
||||
// Additional setup goes here.
|
||||
});
|
||||
|
||||
test('First Test', () {
|
||||
expect(2, 2);
|
||||
});
|
||||
});
|
||||
}
|
||||
65
example/bin/main.dart
Normal file
65
example/bin/main.dart
Normal file
@@ -0,0 +1,65 @@
|
||||
import 'dart:async';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:dart_di/dart_di.dart';
|
||||
|
||||
void main() async {
|
||||
final dataModule = new DiContainer()
|
||||
..bind<ApiClient>().toValue(new ApiClientMock())
|
||||
..bind<DataRepository>()
|
||||
.toFactory1<ApiClient>((c) => new NetworkDataRepository(c))
|
||||
..bind<DataBloc>().toFactory1<DataRepository>((s) => new DataBloc(s));
|
||||
|
||||
final dataBloc = dataModule.resolve<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
|
||||
await dataBloc.fetchData();
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
Stream<String> get data => _dataController.stream;
|
||||
StreamController<String> _dataController = new StreamController.broadcast();
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
Future<void> fetchData() async {
|
||||
try {
|
||||
_dataController.sink.add(await _dataRepository.getData());
|
||||
} catch (e) {
|
||||
_dataController.sink.addError(e);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_dataController.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class DataRepository {
|
||||
Future<String> getData();
|
||||
}
|
||||
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async => await _apiClient.sendRequest(
|
||||
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String url, String token, Map requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
return 'hello world';
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
name: example
|
||||
version: 1.0.0
|
||||
author: "Sergey Penkovsky <sergey.penkovsky@gmail.com>"
|
||||
homepage: localhost
|
||||
publish_to: none
|
||||
|
||||
environment:
|
||||
sdk: ">=2.12.0 <3.0.0"
|
||||
|
||||
|
||||
dependencies:
|
||||
meta: ^1.3.0
|
||||
|
||||
cherrypick:
|
||||
dart_di:
|
||||
path: ../
|
||||
|
||||
dev_dependencies:
|
||||
53
examples/client_app/.gitignore
vendored
53
examples/client_app/.gitignore
vendored
@@ -1,53 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
.pub/
|
||||
/build/
|
||||
|
||||
# Symbolication related
|
||||
app.*.symbols
|
||||
|
||||
# Obfuscation related
|
||||
app.*.map.json
|
||||
|
||||
# Android Studio will place build artifacts here
|
||||
/android/app/debug
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
|
||||
|
||||
pubspec_overrides.yaml
|
||||
|
||||
|
||||
**/*.g.dart
|
||||
**/*.gr.dart
|
||||
**/*.freezed.dart
|
||||
**/*.cherrypick_injectable.g.dart
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "4cf269e36de2573851eaef3c763994f8f9be494d"
|
||||
channel: "stable"
|
||||
|
||||
project_type: app
|
||||
|
||||
# Tracks metadata for the flutter migrate command
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
base_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
- platform: web
|
||||
create_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
base_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
|
||||
# User provided section
|
||||
|
||||
# List of Local paths (relative to this file) that should be
|
||||
# ignored by the migrate tool.
|
||||
#
|
||||
# Files that are not part of the templates will be ignored by default.
|
||||
unmanaged_files:
|
||||
- 'lib/main.dart'
|
||||
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||
@@ -1,16 +0,0 @@
|
||||
# client_app
|
||||
|
||||
A new Flutter project.
|
||||
|
||||
## Getting Started
|
||||
|
||||
This project is a starting point for a Flutter application.
|
||||
|
||||
A few resources to get you started if this is your first Flutter project:
|
||||
|
||||
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
|
||||
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
|
||||
|
||||
For help getting started with Flutter development, view the
|
||||
[online documentation](https://docs.flutter.dev/), which offers tutorials,
|
||||
samples, guidance on mobile development, and a full API reference.
|
||||
@@ -1,28 +0,0 @@
|
||||
# This file configures the analyzer, which statically analyzes Dart code to
|
||||
# check for errors, warnings, and lints.
|
||||
#
|
||||
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
|
||||
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
|
||||
# invoked from the command line by running `flutter analyze`.
|
||||
|
||||
# The following line activates a set of recommended lints for Flutter apps,
|
||||
# packages, and plugins designed to encourage good coding practices.
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
linter:
|
||||
# The lint rules applied to this project can be customized in the
|
||||
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
|
||||
# included above or to enable additional rules. A list of all available lints
|
||||
# and their documentation is published at https://dart.dev/lints.
|
||||
#
|
||||
# Instead of disabling a lint rule for the entire project in the
|
||||
# section below, it can also be suppressed for a single line of code
|
||||
# or a specific dart file by using the `// ignore: name_of_lint` and
|
||||
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
|
||||
# producing the lint.
|
||||
rules:
|
||||
# avoid_print: false # Uncomment to disable the `avoid_print` rule
|
||||
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
|
||||
|
||||
# Additional information about this file can be found at
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
@@ -1,30 +0,0 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:client_app/my_home_page.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cherrypick_flutter/cherrypick_flutter.dart';
|
||||
|
||||
void main() {
|
||||
// Здесь происходит инициализация рутового скоупа и привязка зависимостей
|
||||
CherryPick.openRootScope().installModules([
|
||||
// Создаем модуль, который будет предоставлять UseCase
|
||||
]);
|
||||
|
||||
runApp(
|
||||
const CherryPickProvider(
|
||||
child: MyApp(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CherryPickProvider(
|
||||
child: MaterialApp(
|
||||
home: MyHomePage(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'use_case.dart';
|
||||
|
||||
class MyHomePage extends StatelessWidget {
|
||||
late final UseCase useCase;
|
||||
|
||||
// ignore: prefer_const_constructors_in_immutables
|
||||
MyHomePage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
//_inject(context); // Make sure this function is called in context
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Example App'),
|
||||
),
|
||||
body: Center(
|
||||
child: Text(useCase.fetchData()),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
class UseCase {
|
||||
String fetchData() => "Data fetched by UseCase";
|
||||
}
|
||||
@@ -1,593 +0,0 @@
|
||||
# Generated by pub
|
||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||
packages:
|
||||
_fe_analyzer_shared:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: _fe_analyzer_shared
|
||||
sha256: e55636ed79578b9abca5fecf9437947798f5ef7456308b5cb85720b793eac92f
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "82.0.0"
|
||||
analyzer:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: analyzer
|
||||
sha256: "904ae5bb474d32c38fb9482e2d925d5454cda04ddd0e55d2e6826bc72f6ba8c0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.4.5"
|
||||
args:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: args
|
||||
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.7.0"
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: async
|
||||
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.12.0"
|
||||
boolean_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: boolean_selector
|
||||
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
build:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build
|
||||
sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.2"
|
||||
build_config:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_config
|
||||
sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
build_daemon:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_daemon
|
||||
sha256: "79b2aef6ac2ed00046867ed354c88778c9c0f029df8a20fe10b5436826721ef9"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.2"
|
||||
build_resolvers:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_resolvers
|
||||
sha256: b9e4fda21d846e192628e7a4f6deda6888c36b5b69ba02ff291a01fd529140f0
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.4"
|
||||
build_runner:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: build_runner
|
||||
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.15"
|
||||
build_runner_core:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: build_runner_core
|
||||
sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.0.0"
|
||||
built_collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: built_collection
|
||||
sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.1.1"
|
||||
built_value:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: built_value
|
||||
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.9.5"
|
||||
characters:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: characters
|
||||
sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
checked_yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: checked_yaml
|
||||
sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.3"
|
||||
cherrypick:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick"
|
||||
relative: true
|
||||
source: path
|
||||
version: "2.2.0-dev.1"
|
||||
cherrypick_annotations:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick_annotations"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.0-dev.1"
|
||||
cherrypick_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../../cherrypick_flutter"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.2-dev.1"
|
||||
cherrypick_generator:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
path: "../../cherrypick_generator"
|
||||
relative: true
|
||||
source: path
|
||||
version: "1.1.0-dev.3"
|
||||
clock:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: clock
|
||||
sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
code_builder:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: code_builder
|
||||
sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.10.1"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: collection
|
||||
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.19.1"
|
||||
convert:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: convert
|
||||
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.2"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: crypto
|
||||
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.6"
|
||||
cupertino_icons:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: cupertino_icons
|
||||
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.8"
|
||||
dart_style:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: dart_style
|
||||
sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: fake_async
|
||||
sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.2"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.1"
|
||||
fixnum:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: fixnum
|
||||
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: flutter_lints
|
||||
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
flutter_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
frontend_server_client:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: frontend_server_client
|
||||
sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.0"
|
||||
glob:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: glob
|
||||
sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
graphs:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: graphs
|
||||
sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http
|
||||
sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
http_multi_server:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http_multi_server
|
||||
sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.2"
|
||||
http_parser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http_parser
|
||||
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.2"
|
||||
io:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: io
|
||||
sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.5"
|
||||
js:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: js
|
||||
sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.1"
|
||||
json_annotation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: json_annotation
|
||||
sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.9.0"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker
|
||||
sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "10.0.8"
|
||||
leak_tracker_flutter_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_flutter_testing
|
||||
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.9"
|
||||
leak_tracker_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_testing
|
||||
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lints
|
||||
sha256: "3315600f3fb3b135be672bf4a178c55f274bebe368325ae18462c89ac1e3b413"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
logging:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: logging
|
||||
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.0"
|
||||
matcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: matcher
|
||||
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.12.17"
|
||||
material_color_utilities:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: material_color_utilities
|
||||
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.11.1"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.16.0"
|
||||
mime:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: mime
|
||||
sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
package_config:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: package_config
|
||||
sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path
|
||||
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.9.1"
|
||||
pool:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pool
|
||||
sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.5.1"
|
||||
pub_semver:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pub_semver
|
||||
sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
pubspec_parse:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pubspec_parse
|
||||
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
shelf:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shelf
|
||||
sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.1"
|
||||
shelf_web_socket:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shelf_web_socket
|
||||
sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.1"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
source_gen:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: source_gen
|
||||
sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
source_span:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: source_span
|
||||
sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.10.1"
|
||||
stack_trace:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stack_trace
|
||||
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.12.1"
|
||||
stream_channel:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stream_channel
|
||||
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.4"
|
||||
stream_transform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stream_transform
|
||||
sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
string_scanner:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: string_scanner
|
||||
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.1"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: term_glyph
|
||||
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.2"
|
||||
test_api:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: test_api
|
||||
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.4"
|
||||
timing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: timing
|
||||
sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.2"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: typed_data
|
||||
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
vector_math:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vector_math
|
||||
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.4"
|
||||
vm_service:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vm_service
|
||||
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "14.3.1"
|
||||
watcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: watcher
|
||||
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web
|
||||
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
web_socket:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web_socket
|
||||
sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.1"
|
||||
web_socket_channel:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web_socket_channel
|
||||
sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.3"
|
||||
yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: yaml
|
||||
sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.3"
|
||||
sdks:
|
||||
dart: ">=3.7.0-0 <4.0.0"
|
||||
flutter: ">=3.18.0-18.0.pre.54"
|
||||
@@ -1,70 +0,0 @@
|
||||
name: client_app
|
||||
description: "A new Flutter project."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.0.0+1
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
cherrypick: ^2.2.0-dev.1
|
||||
cherrypick_flutter: ^1.1.2-dev.1
|
||||
|
||||
cherrypick_annotations: ^1.1.0-dev.1
|
||||
|
||||
cupertino_icons: ^1.0.8
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
|
||||
flutter_lints: ^5.0.0
|
||||
|
||||
cherrypick_generator: ^1.1.0-dev.4
|
||||
build_runner: ^2.4.15
|
||||
|
||||
# For information on the generic Dart part of this file, see the
|
||||
# following page: https://dart.dev/tools/pub/pubspec
|
||||
|
||||
# The following section is specific to Flutter packages.
|
||||
flutter:
|
||||
|
||||
# The following line ensures that the Material Icons font is
|
||||
# included with your application, so that you can use the icons in
|
||||
# the material Icons class.
|
||||
uses-material-design: true
|
||||
|
||||
# To add assets to your application, add an assets section, like this:
|
||||
# assets:
|
||||
# - images/a_dot_burr.jpeg
|
||||
# - images/a_dot_ham.jpeg
|
||||
|
||||
# An image asset can refer to one or more resolution-specific "variants", see
|
||||
# https://flutter.dev/to/resolution-aware-images
|
||||
|
||||
# For details regarding adding assets from package dependencies, see
|
||||
# https://flutter.dev/to/asset-from-package
|
||||
|
||||
# To add custom fonts to your application, add a fonts section here,
|
||||
# in this "flutter" section. Each entry in this list should have a
|
||||
# "family" key with the font family name, and a "fonts" key with a
|
||||
# list giving the asset and other descriptors for the font. For
|
||||
# example:
|
||||
# fonts:
|
||||
# - family: Schyler
|
||||
# fonts:
|
||||
# - asset: fonts/Schyler-Regular.ttf
|
||||
# - asset: fonts/Schyler-Italic.ttf
|
||||
# style: italic
|
||||
# - family: Trajan Pro
|
||||
# fonts:
|
||||
# - asset: fonts/TrajanPro.ttf
|
||||
# - asset: fonts/TrajanPro_Bold.ttf
|
||||
# weight: 700
|
||||
#
|
||||
# For details regarding fonts from package dependencies,
|
||||
# see https://flutter.dev/to/font-from-package
|
||||
@@ -1,31 +0,0 @@
|
||||
// This is a basic Flutter widget test.
|
||||
//
|
||||
// To perform an interaction with a widget in your test, use the WidgetTester
|
||||
// utility in the flutter_test package. For example, you can send tap and scroll
|
||||
// gestures. You can also use WidgetTester to find child widgets in the widget
|
||||
// tree, read text, and verify that the values of widget properties are correct.
|
||||
|
||||
//import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
//import 'package:client_app/main.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
|
||||
expect(1, 1);
|
||||
// Build our app and trigger a frame.
|
||||
//await tester.pumpWidget(const MyApp());
|
||||
|
||||
//// Verify that our counter starts at 0.
|
||||
//expect(find.text('0'), findsOneWidget);
|
||||
//expect(find.text('1'), findsNothing);
|
||||
|
||||
//// Tap the '+' icon and trigger a frame.
|
||||
//await tester.tap(find.byIcon(Icons.add));
|
||||
//await tester.pump();
|
||||
|
||||
//// Verify that our counter has incremented.
|
||||
//expect(find.text('0'), findsNothing);
|
||||
//expect(find.text('1'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 917 B |
Binary file not shown.
|
Before Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 8.1 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 5.5 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 20 KiB |
@@ -1,38 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<!--
|
||||
If you are serving your web app in a path other than the root, change the
|
||||
href value below to reflect the base path you are serving from.
|
||||
|
||||
The path provided below has to start and end with a slash "/" in order for
|
||||
it to work correctly.
|
||||
|
||||
For more details:
|
||||
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
|
||||
|
||||
This is a placeholder for base href that will be replaced by the value of
|
||||
the `--base-href` argument provided to `flutter build`.
|
||||
-->
|
||||
<base href="$FLUTTER_BASE_HREF">
|
||||
|
||||
<meta charset="UTF-8">
|
||||
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
|
||||
<meta name="description" content="A new Flutter project.">
|
||||
|
||||
<!-- iOS meta tags & icons -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
<meta name="apple-mobile-web-app-title" content="client_app">
|
||||
<link rel="apple-touch-icon" href="icons/Icon-192.png">
|
||||
|
||||
<!-- Favicon -->
|
||||
<link rel="icon" type="image/png" href="favicon.png"/>
|
||||
|
||||
<title>client_app</title>
|
||||
<link rel="manifest" href="manifest.json">
|
||||
</head>
|
||||
<body>
|
||||
<script src="flutter_bootstrap.js" async></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"name": "client_app",
|
||||
"short_name": "client_app",
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"background_color": "#0175C2",
|
||||
"theme_color": "#0175C2",
|
||||
"description": "A new Flutter project.",
|
||||
"orientation": "portrait-primary",
|
||||
"prefer_related_applications": false,
|
||||
"icons": [
|
||||
{
|
||||
"src": "icons/Icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "icons/Icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "icons/Icon-maskable-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "icons/Icon-maskable-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
48
examples/postly/.gitignore
vendored
48
examples/postly/.gitignore
vendored
@@ -1,48 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
.pub/
|
||||
/build/
|
||||
|
||||
# Symbolication related
|
||||
app.*.symbols
|
||||
|
||||
# Obfuscation related
|
||||
app.*.map.json
|
||||
|
||||
# Android Studio will place build artifacts here
|
||||
/android/app/debug
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
|
||||
|
||||
**/*.g.dart
|
||||
**/*.gr.dart
|
||||
**/*.freezed.dart
|
||||
@@ -1,30 +0,0 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "4cf269e36de2573851eaef3c763994f8f9be494d"
|
||||
channel: "stable"
|
||||
|
||||
project_type: app
|
||||
|
||||
# Tracks metadata for the flutter migrate command
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
base_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
- platform: web
|
||||
create_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
base_revision: 4cf269e36de2573851eaef3c763994f8f9be494d
|
||||
|
||||
# User provided section
|
||||
|
||||
# List of Local paths (relative to this file) that should be
|
||||
# ignored by the migrate tool.
|
||||
#
|
||||
# Files that are not part of the templates will be ignored by default.
|
||||
unmanaged_files:
|
||||
- 'lib/main.dart'
|
||||
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||
@@ -1,16 +0,0 @@
|
||||
# postly
|
||||
|
||||
A new Flutter project.
|
||||
|
||||
## Getting Started
|
||||
|
||||
This project is a starting point for a Flutter application.
|
||||
|
||||
A few resources to get you started if this is your first Flutter project:
|
||||
|
||||
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
|
||||
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
|
||||
|
||||
For help getting started with Flutter development, view the
|
||||
[online documentation](https://docs.flutter.dev/), which offers tutorials,
|
||||
samples, guidance on mobile development, and a full API reference.
|
||||
@@ -1,28 +0,0 @@
|
||||
# This file configures the analyzer, which statically analyzes Dart code to
|
||||
# check for errors, warnings, and lints.
|
||||
#
|
||||
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
|
||||
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
|
||||
# invoked from the command line by running `flutter analyze`.
|
||||
|
||||
# The following line activates a set of recommended lints for Flutter apps,
|
||||
# packages, and plugins designed to encourage good coding practices.
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
linter:
|
||||
# The lint rules applied to this project can be customized in the
|
||||
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
|
||||
# included above or to enable additional rules. A list of all available lints
|
||||
# and their documentation is published at https://dart.dev/lints.
|
||||
#
|
||||
# Instead of disabling a lint rule for the entire project in the
|
||||
# section below, it can also be suppressed for a single line of code
|
||||
# or a specific dart file by using the `// ignore: name_of_lint` and
|
||||
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
|
||||
# producing the lint.
|
||||
rules:
|
||||
# avoid_print: false # Uncomment to disable the `avoid_print` rule
|
||||
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
|
||||
|
||||
# Additional information about this file can be found at
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
@@ -1,3 +0,0 @@
|
||||
description: This file stores settings for Dart & Flutter DevTools.
|
||||
documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states
|
||||
extensions:
|
||||
@@ -1,35 +0,0 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import 'domain/repository/post_repository.dart';
|
||||
import 'presentation/bloc/post_bloc.dart';
|
||||
import 'router/app_router.dart';
|
||||
|
||||
part 'app.inject.cherrypick.g.dart';
|
||||
|
||||
@injectable()
|
||||
class MyApp extends StatelessWidget with _$MyApp {
|
||||
final _appRouter = AppRouter();
|
||||
|
||||
@named('repo')
|
||||
@inject()
|
||||
late final PostRepository repository;
|
||||
|
||||
MyApp({super.key}) {
|
||||
_inject(this);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocProvider(
|
||||
create: (_) => PostBloc(repository),
|
||||
child: MaterialApp.router(
|
||||
routeInformationParser: _appRouter.defaultRouteParser(),
|
||||
routerDelegate: _appRouter.delegate(),
|
||||
theme: ThemeData.light(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'post_model.freezed.dart';
|
||||
part 'post_model.g.dart';
|
||||
|
||||
@freezed
|
||||
class PostModel with _$PostModel {
|
||||
const factory PostModel({
|
||||
required int id,
|
||||
required String title,
|
||||
required String body,
|
||||
}) = _PostModel;
|
||||
|
||||
factory PostModel.fromJson(Map<String, dynamic> json) =>
|
||||
_$PostModelFromJson(json);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import 'package:retrofit/retrofit.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../model/post_model.dart';
|
||||
|
||||
part 'json_placeholder_api.g.dart';
|
||||
|
||||
@RestApi(baseUrl: 'https://jsonplaceholder.typicode.com/')
|
||||
abstract class JsonPlaceholderApi {
|
||||
factory JsonPlaceholderApi(Dio dio, {String baseUrl}) = _JsonPlaceholderApi;
|
||||
|
||||
@GET('/posts')
|
||||
Future<List<PostModel>> getPosts();
|
||||
|
||||
@GET('/posts/{id}')
|
||||
Future<PostModel> getPost(@Path('id') int id);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import '../domain/entity/post.dart';
|
||||
import '../domain/repository/post_repository.dart';
|
||||
import 'network/json_placeholder_api.dart';
|
||||
|
||||
class PostRepositoryImpl implements PostRepository {
|
||||
final JsonPlaceholderApi api;
|
||||
|
||||
PostRepositoryImpl(this.api);
|
||||
|
||||
@override
|
||||
Future<Either<Exception, List<Post>>> getPosts() async {
|
||||
try {
|
||||
final posts = await api.getPosts();
|
||||
return Right(posts
|
||||
.map((e) => Post(id: e.id, title: e.title, body: e.body))
|
||||
.toList());
|
||||
} catch (e) {
|
||||
return Left(Exception(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Exception, Post>> getPost(int id) async {
|
||||
try {
|
||||
final post = await api.getPost(id);
|
||||
return Right(Post(id: post.id, title: post.title, body: post.body));
|
||||
} catch (e) {
|
||||
return Left(Exception(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import '../data/network/json_placeholder_api.dart';
|
||||
import '../data/post_repository_impl.dart';
|
||||
import '../domain/repository/post_repository.dart';
|
||||
|
||||
part 'app_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class AppModule extends Module {
|
||||
@instance()
|
||||
int timeout() => 1000;
|
||||
|
||||
@instance()
|
||||
@named('Delay')
|
||||
Future<int> delay() => Future.value(1000);
|
||||
|
||||
@instance()
|
||||
@named('Size')
|
||||
Future<int> size() async => 10;
|
||||
|
||||
@instance()
|
||||
@named('baseUrl')
|
||||
String baseUrl() => "https://google.com";
|
||||
|
||||
@provide()
|
||||
@named('Delay1')
|
||||
Future<int> delay1() => Future.value(1000);
|
||||
|
||||
@provide()
|
||||
@named('Size1')
|
||||
Future<int> size1() async => 10;
|
||||
|
||||
@provide()
|
||||
@singleton()
|
||||
@named('dio')
|
||||
Dio dio(@named('baseUrl') String baseUrl) =>
|
||||
Dio(BaseOptions(baseUrl: baseUrl));
|
||||
|
||||
@provide()
|
||||
@singleton()
|
||||
JsonPlaceholderApi api(@named('dio') Dio dio) => JsonPlaceholderApi(dio);
|
||||
|
||||
@provide()
|
||||
@named('repo')
|
||||
PostRepository repo(JsonPlaceholderApi api) => PostRepositoryImpl(api);
|
||||
|
||||
@provide()
|
||||
@named('TestProvideWithParams')
|
||||
String testProvideWithParams(@params() dynamic params) => "hello $params";
|
||||
|
||||
@provide()
|
||||
@named('TestProvideAsyncWithParams')
|
||||
Future<String> testProvideAsyncWithParams(@params() dynamic params) async =>
|
||||
"hello $params";
|
||||
|
||||
@provide()
|
||||
@named('TestProvideWithParams1')
|
||||
String testProvideWithParams1(
|
||||
@named('baseUrl') String baseUrl, @params() dynamic params) =>
|
||||
"hello $params";
|
||||
|
||||
@provide()
|
||||
@named('TestProvideAsyncWithParams1')
|
||||
Future<String> testProvideAsyncWithParams1(
|
||||
@named('baseUrl') String baseUrl, @params() dynamic params) async =>
|
||||
"hello $params";
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'post.freezed.dart';
|
||||
|
||||
@freezed
|
||||
class Post with _$Post {
|
||||
const factory Post({
|
||||
required int id,
|
||||
required String title,
|
||||
required String body,
|
||||
}) = _Post;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import '../entity/post.dart';
|
||||
|
||||
abstract class PostRepository {
|
||||
Future<Either<Exception, List<Post>>> getPosts();
|
||||
Future<Either<Exception, Post>> getPost(int id);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user