Compare commits

...

76 Commits

Author SHA1 Message Date
Sergey Penkovsky
f8340c6a84 chore(release): publish packages
- cherrypick@2.2.0-dev.1
 - cherrypick_generator@1.1.0-dev.1
 - cherrypick_flutter@1.1.2-dev.1
2025-05-22 23:52:55 +03:00
Sergey Penkovsky
62a1655728 fix: fix warnings 2025-05-22 23:52:02 +03:00
Sergey Penkovsky
fc941c0041 update deps 2025-05-22 23:50:55 +03:00
Sergey Penkovsky
5161fa19b6 refactor code 2025-05-22 23:32:26 +03:00
Sergey Penkovsky
8093f077b1 fix: optimize code 2025-05-22 23:27:41 +03:00
Sergey Penkovsky
45b93db6f5 fix pubspecs 2025-05-22 16:58:59 +03:00
Sergey Penkovsky
1741256f37 chore(release): publish packages
- cherrypick@2.2.0-dev.0
 - cherrypick_annotations@1.1.0-dev.0
 - cherrypick_flutter@1.1.2-dev.0
 - cherrypick_generator@1.1.0-dev.0
2025-05-22 16:54:26 +03:00
Sergey Penkovsky
6aa76e4041 fix pubspecs 2025-05-22 16:53:29 +03:00
Sergey Penkovsky
b4970fcf43 doc: update readme 2025-05-22 16:26:33 +03:00
Sergey Penkovsky
0874cbe43a doc: update documentations 2025-05-22 16:06:38 +03:00
Sergey Penkovsky
3bbecfb8ac doc: update documentations 2025-05-22 16:05:09 +03:00
Sergey Penkovsky
c47418d922 update readme 2025-05-22 15:18:16 +03:00
Sergey Penkovsky
9bbfe2a726 added documentations 2025-05-22 13:52:56 +03:00
Sergey Penkovsky
7490a8e66b refactor code 2025-05-21 15:59:11 +03:00
Sergey Penkovsky
e6d944c5f9 refactor code 2025-05-21 15:50:24 +03:00
Sergey Penkovsky
2bc89062cc fix: fix warning conflict with names 2025-05-21 12:45:52 +03:00
Sergey Penkovsky
df2d90777f feat: implement generator for dynamic params 2025-05-21 12:23:33 +03:00
Sergey Penkovsky
1bdcc71534 feat: implement async mode for instance/provide annotations 2025-05-21 11:05:18 +03:00
Sergey Penkovsky
ad6522856a feat: generate instance async code 2025-05-21 10:40:21 +03:00
Sergey Penkovsky
14dce2aafa feat: implement instance/provide annotations 2025-05-21 00:50:57 +03:00
Sergey Penkovsky
7914d91653 refactor module generator 2025-05-20 19:50:13 +03:00
Sergey Penkovsky
29aa790134 doc: fix comment 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
302e1b6115 doc: update readme 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
3afef18f95 doc: update readme 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
5de737079d doc: add README 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
7e1cb7ab93 doc: update README 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
4c9ff802a6 fix: fix warnings 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
74f13e3fa4 doc: added comments to code 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
7bad0c09c0 write comments to code 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
6e063a4067 modify sample 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
9bc0380a7b fix: fix module generator 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
220f1ed097 feat: implement named dependency 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
a4ee97b79f hotfix 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
ea6eb536dd feat: implement generator for named annotation 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
3d071626e5 fix: fix generator for singletone annotation 2025-05-19 16:12:45 +03:00
Sergey Penkovsky
d1e726aaec feat: implement generator di module 2025-05-19 16:12:44 +03:00
Sergey Penkovsky
b906e927c3 start implement generator code 2025-05-19 16:11:41 +03:00
Sergey Penkovsky
9b0741199c feat: implement annotations 2025-05-19 16:10:44 +03:00
Sergey Penkovsky
7a5880e436 feat: Add async dependency resolution and enhance example
- Implemented async provider methods `toProvideAsync` and `toProvideAsyncWithParams` in `Binding` class, allowing asynchronous initialization with dynamic parameters.
- Added typedefs `AsyncProvider<T>` and `AsyncProviderWithParams<T>` for better type clarity with async operations.
- Introduced async resolution methods `resolveAsync` and `tryResolveAsync` in `Scope` for resolving asynchronous dependencies.
- Updated example in `main.dart` to demonstrate async dependency resolution capabilities.
  - Modified `FeatureModule` to utilize async providers for `DataRepository` and `DataBloc`.
  - Replaced synchronous resolution with `resolveAsync` where applicable.
  - Handled potential errors in dependency resolution with try-catch.
- Removed unnecessary whitespace for cleaner code formatting.
2025-05-19 16:10:43 +03:00
Sergey Penkovsky
de995228a5 update readme 2025-05-19 16:06:51 +03:00
Sergey Penkovsky
2607a69bca Merge pull request #8 from pese-git/refactor
Refactor code and add toInstanceAsync method
2025-05-19 13:44:16 +03:00
Sergey Penkovsky
e91987c635 update tests 2025-05-19 11:14:59 +03:00
Sergey Penkovsky
50652a14a9 implement scope tests 2025-05-19 11:10:10 +03:00
Sergey Penkovsky
869f9123bc feat: implement toInstanceAync binding 2025-05-19 10:55:50 +03:00
Sergey Penkovsky
53dd4a1005 add provide typedef 2025-05-19 10:36:26 +03:00
Sergey Penkovsky
e6f9b13ea4 fix readme and freez deps 2025-05-19 10:26:45 +03:00
Sergey Penkovsky
20e44beea7 chore(release): publish packages
- cherrypick@2.1.0
 - cherrypick_flutter@1.1.1
2025-05-19 10:12:32 +03:00
Sergey Penkovsky
0b3d10b88d Merge pull request #7 from pese-git/develop 2025-05-19 09:24:52 +03:00
Sergey Penkovsky
ed43bf78b8 hide test 2025-05-18 22:59:15 +03:00
Sergey Penkovsky
3cd15bc0c1 hide test 2025-05-18 16:48:37 +03:00
Sergey Penkovsky
bf1b0bd215 fix build scripts 2025-05-18 16:41:48 +03:00
Sergey Penkovsky
9bce40735b init di 2025-05-16 18:09:14 +03:00
Sergey Penkovsky
5cab9164ce modified build scripts 2025-05-16 17:58:02 +03:00
Sergey Penkovsky
0c5db63961 fixed warnings 2025-05-16 17:57:40 +03:00
Sergey Penkovsky
7740717fce implement example 2025-05-16 17:56:57 +03:00
Sergey Penkovsky
a7dc2e0f27 chore(release): publish packages
- cherrypick@2.1.0-dev.1
 - cherrypick_flutter@1.1.1-dev.1
2025-05-16 17:32:26 +03:00
Sergey Penkovsky
cb5f0b23d2 implement example 2025-05-16 17:32:26 +03:00
Sergey Penkovsky
c1b2f9c260 doc: update README 2025-05-16 17:32:26 +03:00
Sergey Penkovsky
80c121d2c9 chore(release): publish packages
- cherrypick@2.1.0-dev.0
 - cherrypick_flutter@1.1.1-dev.0
2025-05-16 17:32:26 +03:00
Sergey Penkovsky
3d24f01e3e doc: update README and example 2025-05-16 17:32:26 +03:00
Sergey Penkovsky
2c39ee48ad implement test 2025-05-16 17:32:26 +03:00
Sergey Penkovsky
28035a1ccd fix warnings 2025-05-16 17:32:25 +03:00
Sergey Penkovsky
1b5cc64324 feat: Add async dependency resolution and enhance example
- Implemented async provider methods `toProvideAsync` and `toProvideAsyncWithParams` in `Binding` class, allowing asynchronous initialization with dynamic parameters.
- Added typedefs `AsyncProvider<T>` and `AsyncProviderWithParams<T>` for better type clarity with async operations.
- Introduced async resolution methods `resolveAsync` and `tryResolveAsync` in `Scope` for resolving asynchronous dependencies.
- Updated example in `main.dart` to demonstrate async dependency resolution capabilities.
  - Modified `FeatureModule` to utilize async providers for `DataRepository` and `DataBloc`.
  - Replaced synchronous resolution with `resolveAsync` where applicable.
  - Handled potential errors in dependency resolution with try-catch.
- Removed unnecessary whitespace for cleaner code formatting.
2025-05-16 17:31:58 +03:00
Sergey Penkovsky
e0e2408bc5 fix: fix warning 2025-05-16 17:31:40 +03:00
Sergey Penkovsky
2fb91ca7cc fix: fix warning 2025-05-16 17:31:23 +03:00
Sergey Penkovsky
f23b14c13b docs: add CONTRIBUTORS.md 2025-05-16 16:43:23 +03:00
Sergey Penkovsky
9255dc2bc3 Update pipeline.yml 2025-05-16 14:17:52 +03:00
Sergey Penkovsky
0d2a6ef023 Update pipeline.yml 2025-05-16 14:11:22 +03:00
Sergey Penkovsky
ec977c06b2 Create pipeline.yml 2025-05-16 14:09:10 +03:00
Sergey Penkovsky
155e5f12a8 fix: fix warnings 2025-05-16 13:10:57 +03:00
Sergey Penkovsky
c5d17e372c fix: fix warnings 2025-05-16 13:06:46 +03:00
Sergey Penkovsky
dba52ccf82 doc: update readme 2025-05-16 13:02:32 +03:00
Sergey Penkovsky
33c97bdf34 formatted changelog 2025-05-16 12:52:59 +03:00
Sergey Penkovsky
e2562d22bb chore(release): publish packages
- cherrypick@2.0.2
 - cherrypick_flutter@1.1.1
2025-05-16 12:46:16 +03:00
Sergey Penkovsky
1a6e3d0b97 Merge pull request #6 from pese-git/fix/resolve_with_params
fix: support passing params when resolving dependency recursively in …
2025-05-16 12:43:42 +03:00
yarashevich_kv
ea8ff1da83 fix: support passing params when resolving dependency recursively in parent scope. 2025-05-16 10:13:59 +03:00
97 changed files with 5234 additions and 568 deletions

38
.github/workflows/pipeline.yml vendored Normal file
View File

@@ -0,0 +1,38 @@
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

6
.gitignore vendored
View File

@@ -7,6 +7,12 @@
.idea/ .idea/
.vscode/ .vscode/
**/*.g.dart
**/*.gr.dart
**/*.freezed.dart
**/*.cherrypick_injectable.g.dart
pubspec_overrides.yaml pubspec_overrides.yaml
melos_cherrypick.iml melos_cherrypick.iml

View File

@@ -3,6 +3,176 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 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 ## 2025-05-03
### Changes ### Changes

4
CONTRIBUTORS.md Normal file
View File

@@ -0,0 +1,4 @@
# Contributors
- Sergey Penkovsky <sergey.penkovsky@gmail.com>
- Klim Yaroshevich <yarashevich_kv@st.by>

171
README.md
View File

@@ -1,100 +1,145 @@
# CherryPick Workspace # CherryPick Workspace
Welcome to the CherryPick Workspace, a comprehensive suite for dependency management in Flutter applications. It consists of the `cherrypick` and `cherrypick_flutter` packages, designed to enhance modularity and testability by providing robust dependency and state management tools. 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.
## Overview ---
- **`cherrypick`**: A Dart library offering core tools for dependency injection and management through modules and scopes. ## Packages Overview
- **`cherrypick_flutter`**: A Flutter-specific library facilitating access to the root scope via the context using `CherryPickProvider`, simplifying state management within the widget tree.
## Repository Structure - **[`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._
- **Packages**: - **[`cherrypick_annotations`](./cherrypick_annotations)**
- `cherrypick`: Core DI functionalities. 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_flutter`: Flutter integration for context-based root scope access.
## Quick Start Guide - **[`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._
### Installation - **[`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.
To add the packages to your project, include the dependencies in your `pubspec.yaml`: ---
## 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 ```yaml
dependencies: dependencies:
cherrypick: any cherrypick: ^<latest-version>
cherrypick_flutter: any cherrypick_annotations: ^<latest-version>
dev_dependencies:
build_runner: ^<latest>
cherrypick_generator: ^<latest-version>
``` ```
Run `flutter pub get` to install the dependencies. For Flutter projects, add:
### Usage ```yaml
dependencies:
cherrypick_flutter: ^<latest-version>
```
#### cherrypick ### 2. Write a DI Module (with annotations)
- **Binding Dependencies**: Use `Binding` to set up dependencies. ```dart
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
import 'package:cherrypick/cherrypick.dart';
```dart @module()
Binding<String>().toInstance("hello world"); abstract class MyModule extends Module {
Binding<String>().toProvide(() => "hello world").singleton(); @singleton()
``` ApiClient apiClient() => ApiClient();
- **Creating Modules**: Define dependencies within a module. @provide()
DataRepository dataRepo(ApiClient client) => DataRepository(client);
```dart @provide()
class AppModule extends Module { String greeting(@params() String name) => 'Hello, $name!';
@override }
void builder(Scope currentScope) { ```
bind<ApiClient>().toInstance(ApiClientMock());
}
}
```
- **Managing Scopes**: Control dependency lifecycles with scopes. ### 3. Generate the bindings
```dart ```sh
final rootScope = Cherrypick.openRootScope(); dart run build_runner build
rootScope.installModules([AppModule()]); # or for Flutter:
final apiClient = rootScope.resolve<ApiClient>(); flutter pub run build_runner build
``` ```
#### cherrypick_flutter The generator will create a `$MyModule` class with binding code.
- **CherryPickProvider**: Wrap your widget tree to access the root scope via context. ### 4. Install and Resolve
```dart ```dart
void main() { final scope = CherryPick.openRootScope()
runApp(CherryPickProvider( ..installModules([$MyModule()]);
rootScope: yourRootScopeInstance,
child: MyApp(),
));
}
```
- **Accessing Root Scope**: Use `CherryPickProvider.of(context).rootScope` to interact with the root scope in your widgets. final repo = scope.resolve<DataRepository>();
final greeting = scope.resolveWithParams<String>('John'); // 'Hello, John!'
```
```dart _For Flutter, wrap your app with `CherryPickProvider` for DI scopes in the widget tree:_
final rootScope = CherryPickProvider.of(context).rootScope;
```
### Example Project ```dart
void main() {
runApp(
CherryPickProvider(child: MyApp()),
);
}
```
Check the `example` directory for a complete demonstration of implementing CherryPick Workspace in a Flutter app. ---
## Features ## Features at a Glance
- [x] Dependency Binding and Resolution -**Fast, lightweight DI** for any Dart/Flutter project
- [x] Custom Module Creation - 🧩 **Modular & hierarchical scopes** (root, subscopes)
- [x] Root and Sub-Scopes - 🔖 **Named/bound/singleton instances** out of the box
- [x] Convenient Root Scope Access in Flutter - 🔄 **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`
## Contributing ---
We welcome contributions from the community. Feel free to open issues or submit pull requests with suggestions and enhancements. ## Example Usage
## License 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
This project is licensed under the Apache License 2.0. You may obtain a copy of the License at [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). ---
## Links ## Contribution & License
- [GitHub Repository](https://github.com/pese-git/cherrypick) - **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.
---
**Happy Cherry Picking! 🍒**

View File

@@ -19,3 +19,6 @@ doc/api/
*.js_ *.js_
*.js.deps *.js.deps
*.js.map *.js.map
# FVM Version Cache
.fvm/

View File

@@ -1,54 +1,69 @@
## 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 ## 2.0.1
- **FIX**: fix warning.
- **FIX**: fix warning. ## 2.0.0
- **FEAT**: support for Dart 3.0.
## 1.1.0
- **FEAT**: verified Dart 3.0 support.
# Changelog ## 1.0.4
- **FIX**: Fixed exception "ConcurrentModificationError".
2.0.0 supported Dart 3.0 ## 1.0.3
- **FEAT**: Added provider with params.
--- ## 1.0.2
- **DOCS**: Updated docs and fixed syntax error.
1.1.0 cheked support Dart 3.0 ## 1.0.1
- **FIX**: Fixed syntax error.
--- ## 1.0.0
- **REFACTOR**: Refactored code and added experimental API.
1.0.4 Fixed exception "ConcurrentModificationError" ## 0.1.2+1
- **FIX**: Fixed initialization error.
--- ## 0.1.2
- **FIX**: Fixed warnings in code.
1.0.3 Added provider with params ## 0.1.1+2
- **MAINT**: Updated libraries and fixed warnings.
--- ## 0.1.1+1
- **MAINT**: Updated pubspec and readme.md.
1.0.2 Updated doc and fixed syntax error ## 0.1.1
- **MAINT**: Updated pubspec.
--- ## 0.1.0
1.0.1 Fixed syntax error - **INIT**: Initial release.
---
1.0.0 Refactored code and added experimental api
---
0.1.2+1 Fixed initializtaion error
---
0.1.2 Fixed warnings in code
---
0.1.1+2 Updated libraries and fixed warnings
---
0.1.1+1 Updated pubspec and readme.md
---
0.1.1 Updated pubspec
---
0.1.0 Initial release
---

View File

@@ -1,74 +1,115 @@
# CherryPick Flutter # CherryPick
`cherrypick_flutter` is a powerful Flutter library for managing and accessing dependencies within your application through a root scope context using `CherryPickProvider`. It offers simplified dependency injection, making your application more modular and test-friendly. `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.
## Quick Start ## Key Concepts
### Main Components in Dependency Injection (DI) ### Binding
#### Binding A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
A Binding is a custom instance configurator, essential for setting up dependencies. It offers the following key methods:
- `toInstance()`: Directly provides an initialized instance. - Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
- `toProvide()`: Accepts a provider function or constructor for lazy initialization. - Lazy providers (sync/async functions)
- `withName()`: Assigns a name to an instance, allowing for retrieval by name. - Provider functions supporting dynamic parameters
- `singleton()`: Marks the instance as a singleton, ensuring only one instance exists in the scope. - Named instances for resolving by string key
- Optional singleton lifecycle
##### Example: #### Example
```dart ```dart
// Direct instance initialization with toInstance() // Provide a direct instance
Binding<String>().toInstance("hello world"); Binding<String>().toInstance("Hello world");
// Or use a provider for lazy initialization // Provide an async direct instance
Binding<String>().toProvide(() => "hello world"); Binding<String>().toInstanceAsync(Future.value("Hello world"));
// Named instance // Provide a lazy sync instance using a factory
Binding<String>().withName("my_string").toInstance("hello world"); Binding<String>().toProvide(() => "Hello world");
// Singleton instance // Provide a lazy async instance using a factory
Binding<String>().toProvide(() => "hello world").singleton(); 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 ### Module
A Module encapsulates bindings, allowing you to organize dependencies logically. To create a custom module, implement the `void builder(Scope currentScope)` method. 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: #### Example
```dart ```dart
class AppModule extends Module { class AppModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<ApiClient>().toInstance(ApiClientMock()); bind<ApiClient>().toInstance(ApiClientMock());
bind<String>().toProvide(() => "Hello world!");
} }
} }
``` ```
#### Scope ### Scope
A Scope is the container that manages your dependency tree, holding modules and instances. Use the scope to access dependencies with the `resolve<T>()` method. 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.
##### Example: You typically work with the root scope, but can also create named subscopes as needed.
#### Example
```dart ```dart
// Open the main scope // Open the main/root scope
final rootScope = Cherrypick.openRootScope(); final rootScope = CherryPick.openRootScope();
// Install custom modules // Install a custom module
rootScope.installModules([AppModule()]); rootScope.installModules([AppModule()]);
// Resolve an instance // Resolve a dependency synchronously
final str = rootScope.resolve<String>(); final str = rootScope.resolve<String>();
// Close the main scope // Resolve a dependency asynchronously
Cherrypick.closeRootScope(); 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 ## Example Application
The following example demonstrates module setup, scope management, and dependency resolution. Below is a complete example illustrating modules, subscopes, async providers, and dependency resolution.
```dart ```dart
import 'dart:async'; import 'dart:async';
@@ -84,51 +125,54 @@ class AppModule extends Module {
} }
class FeatureModule extends Module { class FeatureModule extends Module {
bool isMock; final bool isMock;
FeatureModule({required this.isMock}); FeatureModule({required this.isMock});
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
// Async provider for DataRepository with named dependency selection
bind<DataRepository>() bind<DataRepository>()
.withName("networkRepo") .withName("networkRepo")
.toProvide( .toProvideAsync(() async {
() => NetworkDataRepository( final client = await Future.delayed(
currentScope.resolve<ApiClient>( Duration(milliseconds: 100),
() => currentScope.resolve<ApiClient>(
named: isMock ? "apiClientMock" : "apiClientImpl", named: isMock ? "apiClientMock" : "apiClientImpl",
), ),
), );
) return NetworkDataRepository(client);
})
.singleton(); .singleton();
bind<DataBloc>().toProvide(
() => DataBloc( // Chained async provider for DataBloc
currentScope.resolve<DataRepository>(named: "networkRepo"), bind<DataBloc>().toProvideAsync(
), () async {
final repo = await currentScope.resolveAsync<DataRepository>(
named: "networkRepo");
return DataBloc(repo);
},
); );
} }
} }
void main() async { void main() async {
final scope = openRootScope().installModules([ final scope = CherryPick.openRootScope().installModules([AppModule()]);
AppModule(), final featureScope = scope.openSubScope("featureScope")
]); ..installModules([FeatureModule(isMock: true)]);
final subScope = scope final dataBloc = await featureScope.resolveAsync<DataBloc>();
.openSubScope("featureScope") dataBloc.data.listen(
.installModules([FeatureModule(isMock: true)]); (d) => print('Received data: $d'),
onError: (e) => print('Error: $e'),
final dataBloc = subScope.resolve<DataBloc>(); onDone: () => print('DONE'),
dataBloc.data.listen((d) => print('Received data: $d'), );
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
await dataBloc.fetchData(); await dataBloc.fetchData();
} }
class DataBloc { class DataBloc {
final DataRepository _dataRepository; final DataRepository _dataRepository;
Stream<String> get data => _dataController.stream; Stream<String> get data => _dataController.stream;
StreamController<String> _dataController = new StreamController.broadcast(); final StreamController<String> _dataController = StreamController.broadcast();
DataBloc(this._dataRepository); DataBloc(this._dataRepository);
@@ -152,16 +196,19 @@ abstract class DataRepository {
class NetworkDataRepository implements DataRepository { class NetworkDataRepository implements DataRepository {
final ApiClient _apiClient; final ApiClient _apiClient;
final _token = 'token'; final _token = 'token';
NetworkDataRepository(this._apiClient); NetworkDataRepository(this._apiClient);
@override @override
Future<String> getData() async => await _apiClient.sendRequest( Future<String> getData() async =>
url: 'www.google.com', token: _token, requestBody: {'type': 'data'}); await _apiClient.sendRequest(
url: 'www.google.com',
token: _token,
requestBody: {'type': 'data'},
);
} }
abstract class ApiClient { abstract class ApiClient {
Future sendRequest({@required String url, String token, Map requestBody}); Future sendRequest({@required String? url, String? token, Map? requestBody});
} }
class ApiClientMock implements ApiClient { class ApiClientMock implements ApiClient {
@@ -183,16 +230,23 @@ class ApiClientImpl implements ApiClient {
## Features ## Features
- [x] Main Scope and Sub Scopes - [x] Main Scope and Named Subscopes
- [x] Named Instance Initialization - [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 ## Contributing
We welcome contributions from the community. Please feel free to submit issues or pull requests with suggestions or improvements. Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).
## License ## License
This project is licensed under the Apache License 2.0. You may obtain a copy of the License at [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). 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. **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.

View File

@@ -1,72 +1,73 @@
import 'dart:async'; import 'dart:async';
import 'package:cherrypick/cherrypick.dart'; import 'package:cherrypick/cherrypick.dart';
import 'package:meta/meta.dart';
class AppModule extends Module { class AppModule extends Module {
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<ApiClient>().withName('apiClientMock').toInstance(ApiClientMock()); bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
bind<ApiClient>().withName('apiClientImpl').toInstance(ApiClientImpl()); bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
} }
} }
class FeatureModule extends Module { class FeatureModule extends Module {
bool isMock; final bool isMock;
FeatureModule({required this.isMock}); FeatureModule({required this.isMock});
@override @override
void builder(Scope currentScope) { void builder(Scope currentScope) {
bind<DataRepository>() // Using toProvideAsync for async initialization
.withName('networkRepo') bind<DataRepository>().withName("networkRepo").toProvideAsync(() async {
.toProvide( final client = await Future.delayed(
() => NetworkDataRepository( Duration(milliseconds: 100),
currentScope.resolve<ApiClient>( () => currentScope.resolve<ApiClient>(
named: isMock ? 'apiClientMock' : 'apiClientImpl', named: isMock ? "apiClientMock" : "apiClientImpl"));
), return NetworkDataRepository(client);
), }).singleton();
)
.singleton();
bind<DataBloc>().toProvideWithParams( // Asynchronous initialization of DataBloc
(param) => DataBloc( bind<DataBloc>().toProvideAsync(
currentScope.resolve<DataRepository>(named: 'networkRepo'), () async {
param, final repo = await currentScope.resolveAsync<DataRepository>(
), named: "networkRepo");
return DataBloc(repo);
},
); );
} }
} }
void main() async { Future<void> main() async {
try {
final scope = openRootScope().installModules([ final scope = openRootScope().installModules([
AppModule(), AppModule(),
]); ]);
final subScope = scope final subScope = scope
.openSubScope('featureScope') .openSubScope("featureScope")
.installModules([FeatureModule(isMock: true)]); .installModules([FeatureModule(isMock: true)]);
final dataBloc = subScope.resolve<DataBloc>(params: 'PARAMETER'); // Asynchronous instance resolution
final dataBloc = await subScope.resolveAsync<DataBloc>();
dataBloc.data.listen((d) => print('Received data: $d'), dataBloc.data.listen((d) => print('Received data: $d'),
onError: (e) => print('Error: $e'), onDone: () => print('DONE')); onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
await dataBloc.fetchData(); await dataBloc.fetchData();
} catch (e) {
print('Error resolving dependency: $e');
}
} }
class DataBloc { class DataBloc {
final DataRepository _dataRepository; final DataRepository _dataRepository;
Stream<String> get data => _dataController.stream;
final StreamController<String> _dataController = StreamController.broadcast(); final StreamController<String> _dataController = StreamController.broadcast();
Stream<String> get data => _dataController.stream;
final String param; DataBloc(this._dataRepository);
DataBloc(this._dataRepository, this.param);
Future<void> fetchData() async { Future<void> fetchData() async {
try { try {
_dataController.sink.add(await _dataRepository.getData(param)); _dataController.sink.add(await _dataRepository.getData());
} catch (e) { } catch (e) {
_dataController.sink.addError(e); _dataController.sink.addError(e);
} }
@@ -78,7 +79,7 @@ class DataBloc {
} }
abstract class DataRepository { abstract class DataRepository {
Future<String> getData(String param); Future<String> getData();
} }
class NetworkDataRepository implements DataRepository { class NetworkDataRepository implements DataRepository {
@@ -88,42 +89,24 @@ class NetworkDataRepository implements DataRepository {
NetworkDataRepository(this._apiClient); NetworkDataRepository(this._apiClient);
@override @override
Future<String> getData(String param) async => await _apiClient.sendRequest( Future<String> getData() async => await _apiClient.sendRequest(
url: 'www.google.com', url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
token: _token,
requestBody: {'type': 'data'},
param: param);
} }
abstract class ApiClient { abstract class ApiClient {
Future sendRequest({ Future sendRequest({String url, String token, Map requestBody});
@required String url,
String token,
Map requestBody,
String param,
});
} }
class ApiClientMock implements ApiClient { class ApiClientMock implements ApiClient {
@override @override
Future sendRequest({ Future sendRequest({String? url, String? token, Map? requestBody}) async {
@required String? url, return 'Local Data';
String? token,
Map? requestBody,
String? param,
}) async {
return 'Local Data $param';
} }
} }
class ApiClientImpl implements ApiClient { class ApiClientImpl implements ApiClient {
@override @override
Future sendRequest({ Future sendRequest({String? url, String? token, Map? requestBody}) async {
@required String? url, return 'Network data';
String? token,
Map? requestBody,
String? param,
}) async {
return 'Network data $param';
} }
} }

View File

@@ -1,17 +1,17 @@
/// 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.
///
library cherrypick; //
// 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/binding.dart';
export 'package:cherrypick/src/helper.dart'; export 'package:cherrypick/src/helper.dart';

View File

@@ -1,20 +1,26 @@
/// //
/// Copyright 2021 Sergey Penkovsky <sergey.penkovsky@gmail.com> // Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
/// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at // You may obtain a copy of the License at
/// http://www.apache.org/licenses/LICENSE-2.0 // http://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
/// limitations under the License. // limitations under the License.
/// //
enum Mode { simple, instance, providerInstance, providerInstanceWithParams } enum Mode { simple, instance, providerInstance, providerInstanceWithParams }
typedef Provider<T> = T? Function();
typedef ProviderWithParams<T> = T Function(dynamic params); typedef ProviderWithParams<T> = T Function(dynamic params);
typedef AsyncProvider<T> = Future<T> Function();
typedef AsyncProviderWithParams<T> = Future<T> Function(dynamic params);
/// RU: Класс Binding<T> настраивает параметры экземпляра. /// RU: Класс Binding<T> настраивает параметры экземпляра.
/// ENG: The Binding<T> class configures the settings for the instance. /// ENG: The Binding<T> class configures the settings for the instance.
/// ///
@@ -23,8 +29,13 @@ class Binding<T> {
late Type _key; late Type _key;
late String _name; late String _name;
T? _instance; T? _instance;
T? Function()? _provider; Future<T>? _instanceAsync;
Provider<T>? _provider;
ProviderWithParams<T>? _providerWithParams; ProviderWithParams<T>? _providerWithParams;
AsyncProvider<T>? asyncProvider;
AsyncProviderWithParams<T>? asyncProviderWithParams;
late bool _isSingleton = false; late bool _isSingleton = false;
late bool _isNamed = false; late bool _isNamed = false;
@@ -84,16 +95,37 @@ class Binding<T> {
return this; 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]. /// RU: Инициализация экземляпяра  через провайдер [value].
/// ENG: Initialization instance via provider [value]. /// ENG: Initialization instance via provider [value].
/// ///
/// return [Binding] /// return [Binding]
Binding<T> toProvide(T Function() value) { Binding<T> toProvide(Provider<T> value) {
_mode = Mode.providerInstance; _mode = Mode.providerInstance;
_provider = value; _provider = value;
return this; 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 динамическим параметром. /// RU: Инициализация экземляпяра  через провайдер [value] c динамическим параметром.
/// ENG: Initialization instance via provider [value] with a dynamic param. /// ENG: Initialization instance via provider [value] with a dynamic param.
/// ///
@@ -104,6 +136,16 @@ class Binding<T> {
return this; 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]. /// RU: Инициализация экземляпяра  как сингелтон [value].
/// ENG: Initialization instance as a singelton [value]. /// ENG: Initialization instance as a singelton [value].
/// ///
@@ -119,6 +161,12 @@ class Binding<T> {
/// return [T] /// return [T]
T? get instance => _instance; T? get instance => _instance;
/// RU: Поиск экземпляра.
/// ENG: Resolve instance.
///
/// return [T]
Future<T>? get instanceAsync => _instanceAsync;
/// RU: Поиск экземпляра. /// RU: Поиск экземпляра.
/// ENG: Resolve instance. /// ENG: Resolve instance.
/// ///

View File

@@ -1,15 +1,15 @@
/// //
/// Copyright 2021 Sergey Penkovsky <sergey.penkovsky@gmail.com> // Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
/// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at // You may obtain a copy of the License at
/// http://www.apache.org/licenses/LICENSE-2.0 // http://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
/// limitations under the License. // limitations under the License.
/// //
import 'package:cherrypick/src/scope.dart'; import 'package:cherrypick/src/scope.dart';
abstract class Factory<T> { abstract class Factory<T> {

View File

@@ -1,15 +1,15 @@
/// //
/// Copyright 2021 Sergey Penkovsky <sergey.penkovsky@gmail.com> // Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
/// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at // You may obtain a copy of the License at
/// http://www.apache.org/licenses/LICENSE-2.0 // http://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
/// limitations under the License. // limitations under the License.
/// //
import 'package:cherrypick/src/scope.dart'; import 'package:cherrypick/src/scope.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';

View File

@@ -1,15 +1,15 @@
/// //
/// Copyright 2021 Sergey Penkovsky <sergey.penkovsky@gmail.com> // Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
/// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at // You may obtain a copy of the License at
/// http://www.apache.org/licenses/LICENSE-2.0 // http://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
/// limitations under the License. // limitations under the License.
/// //
import 'dart:collection'; import 'dart:collection';
import 'package:cherrypick/src/binding.dart'; import 'package:cherrypick/src/binding.dart';

View File

@@ -1,15 +1,15 @@
/// //
/// Copyright 2021 Sergey Penkovsky <sergey.penkovsky@gmail.com> // Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
/// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at // You may obtain a copy of the License at
/// http://www.apache.org/licenses/LICENSE-2.0 // http://www.apache.org/licenses/LICENSE-2.0
/// Unless required by applicable law or agreed to in writing, software // Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
/// limitations under the License. // limitations under the License.
/// //
import 'dart:collection'; import 'dart:collection';
import 'package:cherrypick/src/binding.dart'; import 'package:cherrypick/src/binding.dart';
@@ -130,6 +130,54 @@ class Scope {
} }
// 2 Поиск зависимостей в родительском скоупе // 2 Поиск зависимостей в родительском скоупе
return _parentScope?.tryResolve(named: named); 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);
} }
} }

View File

@@ -1,21 +1,20 @@
name: cherrypick name: cherrypick
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects. description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
version: 2.0.1 version: 2.2.0-dev.1
homepage: https://pese-git.github.io/cherrypick-site/ homepage: https://pese-git.github.io/cherrypick-site/
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
environment: environment:
sdk: ">=3.0.0 <4.0.0" sdk: ">=3.5.2 <4.0.0"
dependencies: dependencies:
meta: ^1.3.0 meta: ^1.3.0
dev_dependencies: dev_dependencies:
#pedantic: ^1.11.0 lints: ^5.0.0
test: ^1.25.15
test: ^1.17.2
mockito: ^5.0.6 mockito: ^5.0.6
lints: ^2.1.0 melos: ^6.3.2

View File

@@ -2,295 +2,270 @@ import 'package:cherrypick/src/binding.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
group('Check instance.', () { // --- Instance binding (synchronous) ---
group('Without name.', () { group('Instance Binding (toInstance)', () {
test('Binding resolves null', () { group('Without name', () {
test('Returns null by default', () {
final binding = Binding<int>(); final binding = Binding<int>();
expect(binding.instance, null); expect(binding.instance, null);
}); });
test('Binding check mode', () { test('Sets mode to instance', () {
final expectedValue = 5; final binding = Binding<int>().toInstance(5);
final binding = Binding<int>().toInstance(expectedValue);
expect(binding.mode, Mode.instance); expect(binding.mode, Mode.instance);
}); });
test('Binding check singleton', () { test('isSingleton is true', () {
final expectedValue = 5; final binding = Binding<int>().toInstance(5);
final binding = Binding<int>().toInstance(expectedValue);
expect(binding.isSingleton, true); expect(binding.isSingleton, true);
}); });
test('Binding check value', () { test('Stores value', () {
final expectedValue = 5; final binding = Binding<int>().toInstance(5);
final binding = Binding<int>().toInstance(expectedValue); expect(binding.instance, 5);
expect(binding.instance, expectedValue);
});
test('Binding resolves value', () {
final expectedValue = 5;
final binding = Binding<int>().toInstance(expectedValue);
expect(binding.instance, expectedValue);
}); });
}); });
group('With name.', () { group('With name', () {
test('Binding resolves null', () { test('Returns null by default', () {
final binding = Binding<int>().withName('expectedValue'); final binding = Binding<int>().withName('n');
expect(binding.instance, null); expect(binding.instance, null);
}); });
test('Binding check mode', () { test('Sets mode to instance', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toInstance(5);
final binding =
Binding<int>().withName('expectedValue').toInstance(expectedValue);
expect(binding.mode, Mode.instance); expect(binding.mode, Mode.instance);
}); });
test('Binding check key', () { test('Sets key', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toInstance(5);
final binding =
Binding<int>().withName('expectedValue').toInstance(expectedValue);
expect(binding.key, int); expect(binding.key, int);
}); });
test('Binding check singleton', () { test('isSingleton is true', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toInstance(5);
final binding =
Binding<int>().withName('expectedValue').toInstance(expectedValue);
expect(binding.isSingleton, true); expect(binding.isSingleton, true);
}); });
test('Binding check value', () { test('Stores value', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toInstance(5);
final binding = expect(binding.instance, 5);
Binding<int>().withName('expectedValue').toInstance(expectedValue);
expect(binding.instance, expectedValue);
}); });
test('Binding check value', () { test('Sets name', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toInstance(5);
final binding = expect(binding.name, 'n');
Binding<int>().withName('expectedValue').toInstance(expectedValue);
expect(binding.name, 'expectedValue');
});
test('Binding resolves value', () {
final expectedValue = 5;
final binding =
Binding<int>().withName('expectedValue').toInstance(expectedValue);
expect(binding.instance, expectedValue);
});
}); });
}); });
group('Check provide.', () { test('Multiple toInstance calls change value', () {
group('Without name.', () { final binding = Binding<int>().toInstance(1).toInstance(2);
test('Binding resolves null', () { 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>(); final binding = Binding<int>();
expect(binding.provider, null); expect(binding.provider, null);
}); });
test('Binding check mode', () { test('Sets mode to providerInstance', () {
final expectedValue = 5; final binding = Binding<int>().toProvide(() => 5);
final binding = Binding<int>().toProvide(() => expectedValue);
expect(binding.mode, Mode.providerInstance); expect(binding.mode, Mode.providerInstance);
}); });
test('Binding check singleton', () { test('isSingleton is false by default', () {
final expectedValue = 5; final binding = Binding<int>().toProvide(() => 5);
final binding = Binding<int>().toProvide(() => expectedValue);
expect(binding.isSingleton, false); expect(binding.isSingleton, false);
}); });
test('Binding check value', () { test('Returns provided value', () {
final expectedValue = 5; final binding = Binding<int>().toProvide(() => 5);
final binding = Binding<int>().toProvide(() => expectedValue); expect(binding.provider, 5);
expect(binding.provider, expectedValue);
});
test('Binding resolves value', () {
final expectedValue = 5;
final binding = Binding<int>().toProvide(() => expectedValue);
expect(binding.provider, expectedValue);
}); });
}); });
group('With name.', () { group('With name', () {
test('Binding resolves null', () { test('Returns null by default', () {
final binding = Binding<int>().withName('expectedValue'); final binding = Binding<int>().withName('n');
expect(binding.provider, null); expect(binding.provider, null);
}); });
test('Binding check mode', () { test('Sets mode to providerInstance', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toProvide(() => 5);
final binding = Binding<int>()
.withName('expectedValue')
.toProvide(() => expectedValue);
expect(binding.mode, Mode.providerInstance); expect(binding.mode, Mode.providerInstance);
}); });
test('Binding check key', () { test('Sets key', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toProvide(() => 5);
final binding = Binding<int>()
.withName('expectedValue')
.toProvide(() => expectedValue);
expect(binding.key, int); expect(binding.key, int);
}); });
test('Binding check singleton', () { test('isSingleton is false by default', () {
final expectedValue = 5; final binding = Binding<int>().withName('n').toProvide(() => 5);
final binding = Binding<int>()
.withName('expectedValue')
.toProvide(() => expectedValue);
expect(binding.isSingleton, false); expect(binding.isSingleton, false);
}); });
test('Binding check value', () { test('Returns provided value', () {
final expectedValue = 5; 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>() final binding = Binding<int>()
.withName('expectedValue') .toProvideAsyncWithParams((param) async => 5 + (param as int));
.toProvide(() => expectedValue); expect(await binding.asyncProviderWithParams?.call(3), 8);
expect(binding.provider, expectedValue);
});
test('Binding check value', () {
final expectedValue = 5;
final binding = Binding<int>()
.withName('expectedValue')
.toProvide(() => expectedValue);
expect(binding.name, 'expectedValue');
});
test('Binding resolves value', () {
final expectedValue = 5;
final binding = Binding<int>()
.withName('expectedValue')
.toProvide(() => expectedValue);
expect(binding.provider, expectedValue);
});
}); });
}); });
group('Check singleton provide.', () { // --- Singleton provider binding ---
group('Without name.', () { group('Singleton Provider Binding', () {
test('Binding resolves null', () { group('Without name', () {
test('Returns null if no provider set', () {
final binding = Binding<int>().singleton(); final binding = Binding<int>().singleton();
expect(binding.provider, null); expect(binding.provider, null);
}); });
test('Binding check mode', () { test('Sets mode to providerInstance', () {
final expectedValue = 5; final binding = Binding<int>().toProvide(() => 5).singleton();
final binding =
Binding<int>().toProvide(() => expectedValue).singleton();
expect(binding.mode, Mode.providerInstance); expect(binding.mode, Mode.providerInstance);
}); });
test('Binding check singleton', () { test('isSingleton is true', () {
final expectedValue = 5; final binding = Binding<int>().toProvide(() => 5).singleton();
final binding =
Binding<int>().toProvide(() => expectedValue).singleton();
expect(binding.isSingleton, true); expect(binding.isSingleton, true);
}); });
test('Binding check value', () { test('Returns singleton value', () {
final expectedValue = 5; final binding = Binding<int>().toProvide(() => 5).singleton();
final binding = expect(binding.provider, 5);
Binding<int>().toProvide(() => expectedValue).singleton();
expect(binding.provider, expectedValue);
}); });
test('Binding resolves value', () { test('Returns same value each call and provider only called once', () {
final expectedValue = 5; int counter = 0;
final binding = final binding = Binding<int>().toProvide(() {
Binding<int>().toProvide(() => expectedValue).singleton(); counter++;
expect(binding.provider, expectedValue); return counter;
}).singleton();
final first = binding.provider;
final second = binding.provider;
expect(first, equals(second));
expect(counter, 1);
}); });
}); });
group('With name.', () { group('With name', () {
test('Binding resolves null', () { test('Returns null if no provider set', () {
final binding = Binding<int>().withName('expectedValue').singleton(); final binding = Binding<int>().withName('n').singleton();
expect(binding.provider, null); expect(binding.provider, null);
}); });
test('Binding check mode', () { test('Sets mode to providerInstance', () {
final expectedValue = 5; final binding =
final binding = Binding<int>() Binding<int>().withName('n').toProvide(() => 5).singleton();
.withName('expectedValue')
.toProvide(() => expectedValue)
.singleton();
expect(binding.mode, Mode.providerInstance); expect(binding.mode, Mode.providerInstance);
}); });
test('Binding check key', () { test('Sets key', () {
final expectedValue = 5; final binding =
final binding = Binding<int>() Binding<int>().withName('n').toProvide(() => 5).singleton();
.withName('expectedValue')
.toProvide(() => expectedValue)
.singleton();
expect(binding.key, int); expect(binding.key, int);
}); });
test('Binding check singleton', () { test('isSingleton is true', () {
final expectedValue = 5; final binding =
final binding = Binding<int>() Binding<int>().withName('n').toProvide(() => 5).singleton();
.withName('expectedValue')
.toProvide(() => expectedValue)
.singleton();
expect(binding.isSingleton, true); expect(binding.isSingleton, true);
}); });
test('Binding check value', () { test('Returns singleton value', () {
final expectedValue = 5; final binding =
final binding = Binding<int>() Binding<int>().withName('n').toProvide(() => 5).singleton();
.withName('expectedValue') expect(binding.provider, 5);
.toProvide(() => expectedValue)
.singleton();
expect(binding.provider, expectedValue);
}); });
test('Binding check value', () { test('Sets name', () {
final expectedValue = 5; final binding =
final binding = Binding<int>() Binding<int>().withName('n').toProvide(() => 5).singleton();
.withName('expectedValue') expect(binding.name, 'n');
.toProvide(() => expectedValue) });
.singleton();
expect(binding.name, 'expectedValue');
}); });
test('Binding resolves value', () { test('Chained withName and singleton preserves mode', () {
final expectedValue = 5; final binding =
final binding = Binding<int>() Binding<int>().toProvide(() => 3).withName("named").singleton();
.withName('expectedValue') expect(binding.mode, Mode.providerInstance);
.toProvide(() => expectedValue)
.singleton();
expect(binding.provider, expectedValue);
}); });
}); });
// --- 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);
});
}); });
} }

View File

@@ -3,46 +3,44 @@ import 'package:cherrypick/src/scope.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
group('Without parent scope.', () { // --------------------------------------------------------------------------
test('Parent scope is null.', () { group('Scope & Subscope Management', () {
test('Scope has no parent if constructed with null', () {
final scope = Scope(null); final scope = Scope(null);
expect(scope.parentScope, null); expect(scope.parentScope, null);
}); });
test('Open sub scope.', () { test('Can open and retrieve the same subScope by key', () {
final scope = Scope(null); final scope = Scope(null);
final subScope = scope.openSubScope('subScope'); final subScope = scope.openSubScope('subScope');
expect(scope.openSubScope('subScope'), subScope); expect(scope.openSubScope('subScope'), subScope);
}); });
test("Container throws state error if the value can't be resolved", () { 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); final scope = Scope(null);
expect(() => scope.resolve<String>(), throwsA(isA<StateError>())); expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
}); });
test('Container resolves value after adding a dependency', () { test('Resolves value after adding a dependency', () {
final expectedValue = 'test string'; final expectedValue = 'test string';
final scope = Scope(null) final scope = Scope(null)
.installModules([TestModule<String>(value: expectedValue)]); .installModules([TestModule<String>(value: expectedValue)]);
expect(scope.resolve<String>(), expectedValue); expect(scope.resolve<String>(), expectedValue);
}); });
});
group('With parent scope.', () { test('Returns a value from parent scope', () {
/*
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>()));
});
*/
test('Container resolve() returns a value from parent container.', () {
final expectedValue = 5; final expectedValue = 5;
final parentScope = Scope(null); final parentScope = Scope(null);
final scope = Scope(parentScope); final scope = Scope(parentScope);
@@ -52,8 +50,7 @@ void main() {
expect(scope.resolve<int>(), expectedValue); expect(scope.resolve<int>(), expectedValue);
}); });
test('Container resolve() returns a several value from parent container.', test('Returns several values from parent container', () {
() {
final expectedIntValue = 5; final expectedIntValue = 5;
final expectedStringValue = 'Hello world'; final expectedStringValue = 'Hello world';
final parentScope = Scope(null).installModules([ final parentScope = Scope(null).installModules([
@@ -66,15 +63,126 @@ void main() {
expect(scope.resolve<String>(), expectedStringValue); expect(scope.resolve<String>(), expectedStringValue);
}); });
test("Container resolve() throws a state error if parent hasn't value too.", test("Throws StateError if parent hasn't value too", () {
() {
final parentScope = Scope(null); final parentScope = Scope(null);
final scope = Scope(parentScope); final scope = Scope(parentScope);
expect(() => scope.resolve<int>(), throwsA(isA<StateError>())); 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 { class TestModule<T> extends Module {
final T value; final T value;
final String? name; final String? name;
@@ -89,3 +197,12 @@ class TestModule<T> extends Module {
} }
} }
} }
/// Вспомогательный модуль для подстановки 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 Normal file
View File

@@ -0,0 +1,26 @@
# 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

View File

@@ -0,0 +1,11 @@
## 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.

View File

@@ -0,0 +1,201 @@
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.

View File

@@ -0,0 +1,157 @@
# cherrypick_annotations
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
A lightweight set of Dart annotations designed for dependency injection (DI) frameworks and code generation, inspired by modern approaches like Dagger and Injectable. Works best in tandem 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 (not a singleton).
- **@provide** Marks a method whose return value should be registered as a provider, supporting dependency injection into parameters.
- **@named** Assigns a string name to a binding for keyed resolution.
- **@params** Indicates that a parameter should be injected with runtime-supplied arguments.
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:
build_runner: ^latest
cherrypick_generator:
```
### 2. Annotate your DI modules and providers
```dart
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
import 'package:cherrypick/cherrypick.dart';
@module()
abstract class AppModule extends Module {
@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';
}
```
When used with `cherrypick_generator`, code similar to 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));
}
}
```
---
## Annotation Reference
### `@module`
```dart
@module()
abstract class AppModule extends Module {}
```
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.
---
### `@params`
```dart
@provide()
String greet(@params() dynamic params) => 'Hello $params';
```
Use on method parameters to indicate that this parameter should receive runtime-supplied arguments during dependency resolution (for example, via `.toProvide*((params) => greate(params))` in generated code).
---
## License
Licensed under the [Apache License 2.0](LICENSE).
---
## Contributing
Pull requests and feedback are welcome!
---
## Author
Sergey Penkovsky (<sergey.penkovsky@gmail.com>)

View File

@@ -0,0 +1,30 @@
# 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

View File

@@ -0,0 +1,21 @@
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';

View File

@@ -0,0 +1,41 @@
//
// 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.
//
/// An annotation to specify that a method or class provides a new instance
/// each time it is requested.
///
/// This is typically used to indicate that the annotated binding should
/// not be a singleton and a new object is created for every injection.
///
/// 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());
/// }
/// }
/// ```
// ignore: camel_case_types
final class instance {
const instance();
}

View File

@@ -0,0 +1,37 @@
//
// 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.
//
/// An annotation used to mark a Dart class or library as a module.
///
/// This annotation can be used for tooling, code generation,
/// or to provide additional metadata about the module.
///
/// Example:
/// ```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();
}

View File

@@ -0,0 +1,44 @@
//
// 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.
//
/// An annotation to assign a name or identifier to a class, method, or other element.
///
/// This can be useful for code generation, dependency injection,
/// or providing metadata within a framework.
///
/// Example:
/// ```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 {
/// The assigned name or identifier.
final String value;
/// Creates a [named] annotation with the given [value].
const named(this.value);
}

View File

@@ -0,0 +1,33 @@
//
// 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.
//
/// An annotation to indicate that a parameter is to be injected with run-time provided arguments.
///
/// Use this annotation to mark a method parameter that should receive arguments
/// passed during the resolution of a dependency (for example, through the
/// `.withParams(...)` method in the generated code).
///
/// Example:
/// ```dart
/// @provide()
/// String greet(@params() dynamic params) => 'Hello $params';
/// ```
///
/// This will generate:
/// ```dart
/// bind<String>().toProvideWithParams((args) => greet(args));
/// ```
// ignore: camel_case_types
final class params {
const params();
}

View File

@@ -0,0 +1,42 @@
//
// 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.
//
/// An annotation to indicate that a method provides a dependency to the module.
///
/// This annotation is typically used in conjunction with dependency injection,
/// marking methods whose return value should be registered as a provider.
/// The annotated method can optionally declare dependencies as parameters,
/// which will be resolved and injected automatically.
///
/// Example:
/// ```dart
/// @module()
/// abstract class AppModule extends Module {
/// @provide()
/// Foo foo(Bar bar) => Foo(bar);
/// }
/// ```
///
/// This will generate:
/// ```dart
/// final class $AppModule extends AppModule {
/// @override
/// void builder(Scope currentScope) {
/// bind<Foo>().toProvide(() => foo(currentScope.resolve<Bar>()));
/// }
/// }
/// ```
// ignore: camel_case_types
final class provide {
const provide();
}

View File

@@ -0,0 +1,41 @@
//
// 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.
//
/// An annotation to declare a class as a singleton.
///
/// This can be used to indicate that only one instance of the class
/// should be created, which is often useful in dependency injection
/// frameworks or service locators.
///
/// Example:
/// ```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();
}

View File

@@ -0,0 +1,18 @@
name: cherrypick_annotations
description: Collection annotations.
version: 1.1.0-dev.0
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"
# Add regular dependencies here.
dependencies:
meta: ^1.15.0
# path: ^1.8.0
dev_dependencies:
lints: ^5.0.0
test: ^1.25.8

View File

@@ -0,0 +1,13 @@
import 'package:test/test.dart';
void main() {
group('A group of tests', () {
setUp(() {
// Additional setup goes here.
});
test('First Test', () {
expect(1, 1);
});
});
}

View File

@@ -1,3 +1,24 @@
## 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 ## 1.1.0
- **FIX**: update description. - **FIX**: update description.

View File

@@ -1,6 +1,6 @@
# CherryPick Flutter # CherryPick Flutter
`cherrypick_flutter` is a Flutter library that allows access to the root scope through the context using `CherryPickProvider`. This package is designed to provide a simple and convenient way to interact with the root scope within the widget tree. `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 ## Installation
@@ -11,13 +11,13 @@ dependencies:
cherrypick_flutter: ^1.0.0 cherrypick_flutter: ^1.0.0
``` ```
Then run `flutter pub get` to install the package. Run `flutter pub get` to install the package dependencies.
## Usage ## Usage
### Importing the Package ### Importing the Package
To start using `cherrypick_flutter`, import it into your Dart code: To begin using `cherrypick_flutter`, import it within your Dart file:
```dart ```dart
import 'package:cherrypick_flutter/cherrypick_flutter.dart'; import 'package:cherrypick_flutter/cherrypick_flutter.dart';
@@ -25,7 +25,7 @@ import 'package:cherrypick_flutter/cherrypick_flutter.dart';
### Providing State with `CherryPickProvider` ### Providing State with `CherryPickProvider`
Use `CherryPickProvider` to wrap the part of the widget tree that requires access to the provided state. Use `CherryPickProvider` to encase the widget tree section that requires access to the root or specific subscopes:
```dart ```dart
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -34,35 +34,40 @@ import 'package:cherrypick_flutter/cherrypick_flutter.dart';
void main() { void main() {
runApp( runApp(
CherryPickProvider( CherryPickProvider(
rootScope: yourRootScopeInstance,
child: MyApp(), 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 ### Accessing State
To access the state provided by `CherryPickProvider`, use the `of` method. This is typically done in the `build` method of your widgets. Access the state provided by `CherryPickProvider` within widget `build` methods using the `of` method:
```dart ```dart
class MyWidget extends StatelessWidget { class MyWidget extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final rootScope = CherryPickProvider.of(context).rootScope; final CherryPickProvider cherryPick = CherryPickProvider.of(context);
final rootScope = cherryPick.openRootScope();
return Text('Current state: ${rootScope.someStateValue}'); // Use the rootScope or open a subScope as needed
final subScope = cherryPick.openSubScope(scopeName: "exampleScope");
return Text('Scope accessed!');
} }
} }
``` ```
### Updating State ### Updating State
The `CherryPickProvider` will automatically update its dependents when its state changes. Ensure to override the `updateShouldNotify` method to specify when notifications should occur, as shown in the provided implementation. 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 ## Example
Here is a simple example showing how to implement and use the `CherryPickProvider`. Here is an example illustrating how to implement and utilize `CherryPickProvider` within a Flutter application:
```dart ```dart
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
@@ -70,7 +75,7 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final rootScope = CherryPickProvider.of(context).rootScope; final rootScope = CherryPickProvider.of(context).openRootScope();
return MaterialApp.router( return MaterialApp.router(
routerDelegate: rootScope.resolve<AppRouter>().delegate(), routerDelegate: rootScope.resolve<AppRouter>().delegate(),
@@ -81,10 +86,12 @@ class MyApp extends StatelessWidget {
} }
``` ```
In this example, `CherryPickProvider` accesses and resolves dependencies using root scope and potentially sub-scopes configured by the application.
## Contributing ## Contributing
We welcome contributions from the community. Please open issues and pull requests if you have ideas for improvements. Contributions to improve this library are welcome. Feel free to open issues and submit pull requests on the repository.
## License ## License
This project is licensed under the Apache License 2.0. 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).

View File

@@ -1,15 +1,15 @@
/// library;
/// Copyright 2021 Sergey Penkovsky <sergey.penkovsky@gmail.com> //
/// Licensed under the Apache License, Version 2.0 (the "License"); // Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
/// you may not use this file except in compliance with the License. // Licensed under the Apache License, Version 2.0 (the "License");
/// You may obtain a copy of the License at // you may not use this file except in compliance with the License.
/// http://www.apache.org/licenses/LICENSE-2.0 // You may obtain a copy of the License at
/// Unless required by applicable law or agreed to in writing, software // http://www.apache.org/licenses/LICENSE-2.0
/// distributed under the License is distributed on an "AS IS" BASIS, // Unless required by applicable law or agreed to in writing, software
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // distributed under the License is distributed on an "AS IS" BASIS,
/// See the License for the specific language governing permissions and // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// limitations under the License. // See the License for the specific language governing permissions and
/// // limitations under the License.
library cherrypick_flutter; //
export 'src/cherrypick_provider.dart'; export 'src/cherrypick_provider.dart';

View File

@@ -2,7 +2,7 @@ import 'package:cherrypick/cherrypick.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart';
/// ///
/// Copyright 2021 Sergey Penkovsky <sergey.penkovsky@gmail.com> /// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
/// Licensed under the Apache License, Version 2.0 (the "License"); /// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License. /// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at /// You may obtain a copy of the License at

View File

@@ -1,24 +1,26 @@
name: cherrypick_flutter name: cherrypick_flutter
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`." description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
version: 1.1.0 version: 1.1.2-dev.1
homepage: https://pese-git.github.io/cherrypick-site/ homepage: https://pese-git.github.io/cherrypick-site/
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
environment: environment:
sdk: ^3.5.2 sdk: ">=3.5.2 <4.0.0"
flutter: ">=1.17.0" flutter: ">=3.24.0"
dependencies: dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
cherrypick: ^2.0.0 cherrypick: ^2.2.0-dev.1
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter
flutter_lints: ^4.0.0 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 # For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec # following page: https://dart.dev/tools/pub/pubspec

28
cherrypick_generator/.gitignore vendored Normal file
View File

@@ -0,0 +1,28 @@
# 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

View File

@@ -0,0 +1,22 @@
## 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.

View File

@@ -0,0 +1,201 @@
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.

View File

@@ -0,0 +1,167 @@
# Cherrypick Generator
**Cherrypick Generator** is a Dart code generation library for automatic boilerplate creation in dependency injection (DI) modules. It processes classes annotated with `@module()` (from [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations)) and generates code for registering dependencies, handling singletons, named bindings, runtime parameters, and more.
---
## Features
- **Automatic Binding Generation:**
Generates `bind<Type>()` registration code for every method in a DI module marked with `@module()`.
- **Support for DI Annotations:**
Understands and processes meta-annotations such as `@singleton`, `@named`, `@instance`, `@provide`, and `@params`.
- **Runtime & Compile-Time Parameters:**
Handles both injected (compile-time) and runtime parameters for provider/binding methods.
- **Synchronous & Asynchronous Support:**
Correctly distinguishes between synchronous and asynchronous bindings (including `Future<T>` return types).
- **Named Bindings:**
Allows registration of named services via the `@named()` annotation.
- **Singletons:**
Registers singletons via the `@singleton` annotation.
---
## How It Works
1. **Annotations**
Annotate your module classes and methods using `@module()`, `@instance`, `@provide`, `@singleton`, and `@named` as needed.
2. **Code Scanning**
During the build process (with `build_runner`), the generator scans your annotated classes.
3. **Code Generation**
For each `@module()` class, a new class (with a `$` prefix) is generated.
This class overrides the `builder(Scope)` method to register all bindings.
4. **Binding Logic**
Each binding method's signature and annotations are analyzed. Registration code is generated according to:
- Return type (sync/async)
- Annotations (`@singleton`, `@named`, etc.)
- Parameter list (DI dependencies, `@named`, or `@params` for runtime values)
---
## Example
Given the following annotated Dart code:
```dart
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
@module()
class MyModule {
@singleton
@instance
SomeService provideService(ApiClient client);
@provide
@named('special')
Future<Handler> createHandler(@params Map<String, dynamic> params);
}
```
The generator will output (simplified):
```dart
final class $MyModule extends MyModule {
@override
void builder(Scope currentScope) {
bind<SomeService>()
.toInstance(provideService(currentScope.resolve<ApiClient>()))
.singleton();
bind<Handler>()
.toProvideAsyncWithParams((args) => createHandler(args))
.withName('special');
}
}
```
---
## Generated Code Overview
- **Constructor Registration:**
All non-abstract methods are considered as providers and processed for DI registration.
- **Parameter Handling:**
Each method parameter is analyzed:
- Standard DI dependency: resolved via `currentScope.resolve<Type>()`.
- Named dependency: resolved via `currentScope.resolve<Type>(named: 'name')`.
- Runtime parameter (`@params`): passed through as-is (e.g., `args`).
- **Binding Types:**
Supports both `.toInstance()` and `.toProvide()` (including async variants).
- **Singleton/Named:**
Appends `.singleton()` and/or `.withName('name')` as appropriate.
---
## Usage
1. **Add dependencies**
In your `pubspec.yaml`:
```yaml
dependencies:
cherrypick_annotations: ^x.y.z
dev_dependencies:
build_runner: ^2.1.0
cherrypick_generator: ^x.y.z
```
2. **Apply annotations**
Annotate your DI modules and provider methods as shown above.
3. **Run the generator**
```
dart run build_runner build
# or with Flutter:
flutter pub run build_runner build
```
4. **Import and use the generated code**
The generated files (suffix `.cherrypick.g.dart`) contain your `$YourModule` classes ready for use with your DI framework.
---
## Advanced
- **Customizing Parameter Names:**
Use the `@named('value')` annotation on methods and parameters for named bindings.
- **Runtime Arguments:**
Use `@params` to designate parameters as runtime arguments that are supplied at injection time.
- **Async Factories:**
Methods returning `Future<T>` generate the appropriate `.toProvideAsync()` or `.toInstanceAsync()` bindings.
---
## Developer Notes
- The generator relies on Dart's analyzer, source_gen, and build packages.
- Each class and method is parsed for annotations; missing required annotations (like `@instance` or `@provide`) will result in a generation error.
- The generated code is designed to extend your original module classes while injecting all binding logic.
---
## License
```
Licensed under the Apache License, Version 2.0
```
---
## Contribution
Pull requests and issues are welcome! Please open git issues or submit improvements as needed.
---

View File

@@ -0,0 +1,30 @@
# 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

View File

@@ -0,0 +1,16 @@
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
targets:
$default:
builders:
cherrypick_generator|module_generator:
generate_for:
- lib/**.dart

View File

@@ -0,0 +1,16 @@
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';

View File

@@ -0,0 +1,93 @@
//
// 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()], '.cherrypick.g.dart');

View File

@@ -0,0 +1,75 @@
//
// 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>()";
}
}

View File

@@ -0,0 +1,249 @@
//
// 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:
return isAsyncInstance
? '.toInstanceAsync(($fnArgs) => $methodName($fnArgs))'
: '.toInstance(($fnArgs) => $methodName($fnArgs))';
case BindingType.provide:
default:
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:
default:
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;
// -- 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();
}
}

View File

@@ -0,0 +1,115 @@
//
// 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();
}
}

View File

@@ -0,0 +1,76 @@
//
// 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;
}
}

View File

@@ -0,0 +1,23 @@
name: cherrypick_generator
description: Code generator for cherrypick annotations
version: 1.1.0-dev.1
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"
# Add regular dependencies here.
dependencies:
cherrypick_annotations: ^1.1.0-dev.0
analyzer: ^6.7.0
dart_style: ^2.3.7
build: ^2.4.1
build_runner: ^2.4.13
source_gen: ^1.5.0
dev_dependencies:
lints: ^5.0.0
mockito: ^5.4.4
test: ^1.25.8

View File

@@ -0,0 +1,13 @@
import 'package:test/test.dart';
void main() {
group('A group of tests', () {
setUp(() {
// Additional setup goes here.
});
test('First Test', () {
expect(2, 2);
});
});
}

53
examples/client_app/.gitignore vendored Normal file
View File

@@ -0,0 +1,53 @@
# 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

View File

@@ -0,0 +1,30 @@
# 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'

View File

@@ -0,0 +1,16 @@
# 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.

View File

@@ -0,0 +1,28 @@
# 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

View File

@@ -0,0 +1,30 @@
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(),
),
);
}
}

View File

@@ -0,0 +1,22 @@
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()),
),
);
}
}

View File

@@ -0,0 +1,3 @@
class UseCase {
String fetchData() => "Data fetched by UseCase";
}

View File

@@ -0,0 +1,598 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: f256b0c0ba6c7577c15e2e4e114755640a875e885099367bf6e012b19314c834
url: "https://pub.dev"
source: hosted
version: "72.0.0"
_macros:
dependency: transitive
description: dart
source: sdk
version: "0.3.2"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: b652861553cd3990d8ed361f7979dc6d7053a9ac8843fa73820ab68ce5410139
url: "https://pub.dev"
source: hosted
version: "6.7.0"
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: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
url: "https://pub.dev"
source: hosted
version: "2.11.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
url: "https://pub.dev"
source: hosted
version: "2.1.1"
build:
dependency: transitive
description:
name: build
sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
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: "339086358431fa15d7eca8b6a36e5d783728cf025e559b834f4609a1fcfb7b0a"
url: "https://pub.dev"
source: hosted
version: "2.4.2"
build_runner:
dependency: "direct dev"
description:
name: build_runner
sha256: "028819cfb90051c6b5440c7e574d1896f8037e3c96cf17aaeb054c9311cfbf4d"
url: "https://pub.dev"
source: hosted
version: "2.4.13"
build_runner_core:
dependency: transitive
description:
name: build_runner_core
sha256: f8126682b87a7282a339b871298cc12009cb67109cfa1614d6436fb0289193e0
url: "https://pub.dev"
source: hosted
version: "7.3.2"
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: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
url: "https://pub.dev"
source: hosted
version: "1.3.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.0"
cherrypick_annotations:
dependency: "direct main"
description:
path: "../../cherrypick_annotations"
relative: true
source: path
version: "1.1.0-dev.0"
cherrypick_flutter:
dependency: "direct main"
description:
path: "../../cherrypick_flutter"
relative: true
source: path
version: "1.1.2-dev.0"
cherrypick_generator:
dependency: "direct dev"
description:
path: "../../cherrypick_generator"
relative: true
source: path
version: "1.1.0-dev.0"
clock:
dependency: transitive
description:
name: clock
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
url: "https://pub.dev"
source: hosted
version: "1.1.1"
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: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
url: "https://pub.dev"
source: hosted
version: "1.18.0"
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: "7856d364b589d1f08986e140938578ed36ed948581fbc3bc9aef1805039ac5ab"
url: "https://pub.dev"
source: hosted
version: "2.3.7"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
url: "https://pub.dev"
source: hosted
version: "1.3.1"
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_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: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05"
url: "https://pub.dev"
source: hosted
version: "10.0.5"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806"
url: "https://pub.dev"
source: hosted
version: "3.0.5"
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"
macros:
dependency: transitive
description:
name: macros
sha256: "0acaed5d6b7eab89f63350bccd82119e6c602df0f391260d0e32b5e23db79536"
url: "https://pub.dev"
source: hosted
version: "0.1.2-main.4"
matcher:
dependency: transitive
description:
name: matcher
sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
url: "https://pub.dev"
source: hosted
version: "0.12.16+1"
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: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
url: "https://pub.dev"
source: hosted
version: "1.15.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: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
url: "https://pub.dev"
source: hosted
version: "1.9.0"
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.99"
source_gen:
dependency: transitive
description:
name: source_gen
sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832"
url: "https://pub.dev"
source: hosted
version: "1.5.0"
source_span:
dependency: transitive
description:
name: source_span
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
url: "https://pub.dev"
source: hosted
version: "1.10.0"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
url: "https://pub.dev"
source: hosted
version: "1.11.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
url: "https://pub.dev"
source: hosted
version: "2.1.2"
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: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
url: "https://pub.dev"
source: hosted
version: "1.2.0"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
url: "https://pub.dev"
source: hosted
version: "1.2.1"
test_api:
dependency: transitive
description:
name: test_api
sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb"
url: "https://pub.dev"
source: hosted
version: "0.7.2"
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: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d"
url: "https://pub.dev"
source: hosted
version: "14.2.5"
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.5.2 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54"

View File

@@ -0,0 +1,70 @@
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.0
cupertino_icons: ^1.0.8
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
cherrypick_generator: ^1.1.0-dev.1
build_runner: ^2.4.13
# 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

View File

@@ -0,0 +1,31 @@
// 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.

After

Width:  |  Height:  |  Size: 917 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@@ -0,0 +1,38 @@
<!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>

View File

@@ -0,0 +1,35 @@
{
"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 Normal file
View File

@@ -0,0 +1,48 @@
# 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

30
examples/postly/.metadata Normal file
View File

@@ -0,0 +1,30 @@
# 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'

16
examples/postly/README.md Normal file
View File

@@ -0,0 +1,16 @@
# 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.

View File

@@ -0,0 +1,28 @@
# 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

View File

@@ -0,0 +1,3 @@
description: This file stores settings for Dart & Flutter DevTools.
documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states
extensions:

View File

@@ -0,0 +1,16 @@
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);
}

View File

@@ -0,0 +1,17 @@
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);
}

View File

@@ -0,0 +1,32 @@
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()));
}
}
}

View File

@@ -0,0 +1,69 @@
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.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";
}

View File

@@ -0,0 +1,12 @@
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;
}

View File

@@ -0,0 +1,7 @@
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);
}

View File

@@ -0,0 +1,36 @@
import 'package:cherrypick/cherrypick.dart';
import 'package:flutter/material.dart';
import 'di/app_module.dart';
import 'domain/repository/post_repository.dart';
import 'presentation/bloc/post_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'router/app_router.dart';
void main() {
final scope = CherryPick.openRootScope();
scope.installModules([$AppModule()]);
runApp(MyApp(scope: scope));
}
class MyApp extends StatelessWidget {
final Scope scope;
final _appRouter = AppRouter();
MyApp({super.key, required this.scope});
@override
Widget build(BuildContext context) {
// Получаем репозиторий через injector
final repository = scope.resolve<PostRepository>(named: 'repo');
return BlocProvider(
create: (_) => PostBloc(repository),
child: MaterialApp.router(
routeInformationParser: _appRouter.defaultRouteParser(),
routerDelegate: _appRouter.delegate(),
theme: ThemeData.light(),
),
);
}
}

View File

@@ -0,0 +1,38 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../domain/entity/post.dart';
import '../../domain/repository/post_repository.dart';
part 'post_bloc.freezed.dart';
@freezed
class PostEvent with _$PostEvent {
const factory PostEvent.fetchAll() = _FetchAll;
}
@freezed
class PostState with _$PostState {
const factory PostState.initial() = _Initial;
const factory PostState.loading() = _Loading;
const factory PostState.loaded(List<Post> posts) = _Loaded;
const factory PostState.failure(String message) = _Failure;
}
class PostBloc extends Bloc<PostEvent, PostState> {
final PostRepository repository;
PostBloc(this.repository) : super(const PostState.initial()) {
on<PostEvent>((event, emit) async {
await event.map(
fetchAll: (e) async {
emit(const PostState.loading());
final result = await repository.getPosts();
result.fold(
(l) => emit(PostState.failure(l.toString())),
(r) => emit(PostState.loaded(r)),
);
},
);
});
}
}

View File

@@ -0,0 +1,21 @@
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import '../../domain/entity/post.dart';
@RoutePage()
class PostDetailsPage extends StatelessWidget {
final Post post;
const PostDetailsPage({super.key, required this.post});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Post #${post.id}')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Text(post.body),
),
);
}
}

View File

@@ -0,0 +1,42 @@
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../router/app_router.gr.dart';
import '../bloc/post_bloc.dart';
@RoutePage()
class PostsPage extends StatelessWidget {
const PostsPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) =>
context.read<PostBloc>()..add(const PostEvent.fetchAll()),
child: Scaffold(
appBar: AppBar(title: const Text('Posts')),
body: BlocBuilder<PostBloc, PostState>(
builder: (context, state) {
return state.when(
initial: () => const SizedBox.shrink(),
loading: () => const Center(child: CircularProgressIndicator()),
loaded: (posts) => ListView.builder(
itemCount: posts.length,
itemBuilder: (ctx, i) => ListTile(
title: Text(posts[i].title),
subtitle: Text(posts[i].body),
onTap: () {
AutoRouter.of(context)
.push(PostDetailsRoute(post: posts[i]));
},
),
),
failure: (msg) => Center(child: Text('Error: $msg')),
);
},
),
),
);
}
}

View File

@@ -0,0 +1,12 @@
import 'package:auto_route/auto_route.dart';
import 'app_router.gr.dart';
@AutoRouterConfig()
class AppRouter extends RootStackRouter {
@override
List<AutoRoute> get routes => [
AutoRoute(page: PostsRoute.page, initial: true),
AutoRoute(page: PostDetailsRoute.page),
];
}

View File

@@ -0,0 +1,735 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: f256b0c0ba6c7577c15e2e4e114755640a875e885099367bf6e012b19314c834
url: "https://pub.dev"
source: hosted
version: "72.0.0"
_macros:
dependency: transitive
description: dart
source: sdk
version: "0.3.2"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: b652861553cd3990d8ed361f7979dc6d7053a9ac8843fa73820ab68ce5410139
url: "https://pub.dev"
source: hosted
version: "6.7.0"
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: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
url: "https://pub.dev"
source: hosted
version: "2.11.0"
auto_route:
dependency: "direct main"
description:
name: auto_route
sha256: "1d1bd908a1fec327719326d5d0791edd37f16caff6493c01003689fb03315ad7"
url: "https://pub.dev"
source: hosted
version: "9.3.0+1"
auto_route_generator:
dependency: "direct dev"
description:
name: auto_route_generator
sha256: c9086eb07271e51b44071ad5cff34e889f3156710b964a308c2ab590769e79e6
url: "https://pub.dev"
source: hosted
version: "9.0.0"
bloc:
dependency: transitive
description:
name: bloc
sha256: "52c10575f4445c61dd9e0cafcc6356fdd827c4c64dd7945ef3c4105f6b6ac189"
url: "https://pub.dev"
source: hosted
version: "9.0.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
url: "https://pub.dev"
source: hosted
version: "2.1.1"
build:
dependency: transitive
description:
name: build
sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
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: "339086358431fa15d7eca8b6a36e5d783728cf025e559b834f4609a1fcfb7b0a"
url: "https://pub.dev"
source: hosted
version: "2.4.2"
build_runner:
dependency: "direct dev"
description:
name: build_runner
sha256: "028819cfb90051c6b5440c7e574d1896f8037e3c96cf17aaeb054c9311cfbf4d"
url: "https://pub.dev"
source: hosted
version: "2.4.13"
build_runner_core:
dependency: transitive
description:
name: build_runner_core
sha256: f8126682b87a7282a339b871298cc12009cb67109cfa1614d6436fb0289193e0
url: "https://pub.dev"
source: hosted
version: "7.3.2"
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: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
url: "https://pub.dev"
source: hosted
version: "1.3.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.0"
cherrypick_annotations:
dependency: "direct main"
description:
path: "../../cherrypick_annotations"
relative: true
source: path
version: "1.1.0-dev.0"
cherrypick_generator:
dependency: "direct dev"
description:
path: "../../cherrypick_generator"
relative: true
source: path
version: "1.1.0-dev.0"
clock:
dependency: transitive
description:
name: clock
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
url: "https://pub.dev"
source: hosted
version: "1.1.1"
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: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
url: "https://pub.dev"
source: hosted
version: "1.18.0"
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: "7856d364b589d1f08986e140938578ed36ed948581fbc3bc9aef1805039ac5ab"
url: "https://pub.dev"
source: hosted
version: "2.3.7"
dartz:
dependency: "direct main"
description:
name: dartz
sha256: e6acf34ad2e31b1eb00948692468c30ab48ac8250e0f0df661e29f12dd252168
url: "https://pub.dev"
source: hosted
version: "0.10.1"
dio:
dependency: "direct main"
description:
name: dio
sha256: "253a18bbd4851fecba42f7343a1df3a9a4c1d31a2c1b37e221086b4fa8c8dbc9"
url: "https://pub.dev"
source: hosted
version: "5.8.0+1"
dio_web_adapter:
dependency: transitive
description:
name: dio_web_adapter
sha256: "7586e476d70caecaf1686d21eee7247ea43ef5c345eab9e0cc3583ff13378d78"
url: "https://pub.dev"
source: hosted
version: "2.1.1"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
url: "https://pub.dev"
source: hosted
version: "1.3.1"
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_bloc:
dependency: "direct main"
description:
name: flutter_bloc
sha256: cf51747952201a455a1c840f8171d273be009b932c75093020f9af64f2123e38
url: "https://pub.dev"
source: hosted
version: "9.1.1"
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"
freezed:
dependency: "direct dev"
description:
name: freezed
sha256: "44c19278dd9d89292cf46e97dc0c1e52ce03275f40a97c5a348e802a924bf40e"
url: "https://pub.dev"
source: hosted
version: "2.5.7"
freezed_annotation:
dependency: "direct main"
description:
name: freezed_annotation
sha256: c2e2d632dd9b8a2b7751117abcfc2b4888ecfe181bd9fca7170d9ef02e595fe2
url: "https://pub.dev"
source: hosted
version: "2.4.4"
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_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"
json_serializable:
dependency: "direct dev"
description:
name: json_serializable
sha256: c2fcb3920cf2b6ae6845954186420fca40bc0a8abcc84903b7801f17d7050d7c
url: "https://pub.dev"
source: hosted
version: "6.9.0"
leak_tracker:
dependency: transitive
description:
name: leak_tracker
sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05"
url: "https://pub.dev"
source: hosted
version: "10.0.5"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806"
url: "https://pub.dev"
source: hosted
version: "3.0.5"
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"
macros:
dependency: transitive
description:
name: macros
sha256: "0acaed5d6b7eab89f63350bccd82119e6c602df0f391260d0e32b5e23db79536"
url: "https://pub.dev"
source: hosted
version: "0.1.2-main.4"
matcher:
dependency: transitive
description:
name: matcher
sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
url: "https://pub.dev"
source: hosted
version: "0.12.16+1"
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: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
url: "https://pub.dev"
source: hosted
version: "1.15.0"
mime:
dependency: transitive
description:
name: mime
sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.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: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
url: "https://pub.dev"
source: hosted
version: "1.9.0"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: c15605cd28af66339f8eb6fbe0e541bfe2d1b72d5825efc6598f3e0a31b9ad27
url: "https://pub.dev"
source: hosted
version: "6.0.2"
pool:
dependency: transitive
description:
name: pool
sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a"
url: "https://pub.dev"
source: hosted
version: "1.5.1"
protobuf:
dependency: transitive
description:
name: protobuf
sha256: "68645b24e0716782e58948f8467fd42a880f255096a821f9e7d0ec625b00c84d"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
provider:
dependency: transitive
description:
name: provider
sha256: "4abbd070a04e9ddc287673bf5a030c7ca8b685ff70218720abab8b092f53dd84"
url: "https://pub.dev"
source: hosted
version: "6.1.5"
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"
retrofit:
dependency: "direct main"
description:
name: retrofit
sha256: c6cc9ad3374e6d07008343140a67afffaaa34cdf6bf08d4847d91417a99dcf45
url: "https://pub.dev"
source: hosted
version: "4.4.2"
retrofit_generator:
dependency: "direct dev"
description:
name: retrofit_generator
sha256: f76fdb2b66854690d5a332e7364d7561fc9dc2b3c924d7956ab8070495e21f6a
url: "https://pub.dev"
source: hosted
version: "9.1.5"
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.99"
source_gen:
dependency: transitive
description:
name: source_gen
sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832"
url: "https://pub.dev"
source: hosted
version: "1.5.0"
source_helper:
dependency: transitive
description:
name: source_helper
sha256: "86d247119aedce8e63f4751bd9626fc9613255935558447569ad42f9f5b48b3c"
url: "https://pub.dev"
source: hosted
version: "1.3.5"
source_span:
dependency: transitive
description:
name: source_span
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
url: "https://pub.dev"
source: hosted
version: "1.10.0"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
url: "https://pub.dev"
source: hosted
version: "1.11.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
url: "https://pub.dev"
source: hosted
version: "2.1.2"
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: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
url: "https://pub.dev"
source: hosted
version: "1.2.0"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
url: "https://pub.dev"
source: hosted
version: "1.2.1"
test_api:
dependency: transitive
description:
name: test_api
sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb"
url: "https://pub.dev"
source: hosted
version: "0.7.2"
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: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d"
url: "https://pub.dev"
source: hosted
version: "14.2.5"
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"
xml:
dependency: transitive
description:
name: xml
sha256: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226
url: "https://pub.dev"
source: hosted
version: "6.5.0"
yaml:
dependency: transitive
description:
name: yaml
sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
url: "https://pub.dev"
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.5.2 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54"

View File

@@ -0,0 +1,43 @@
name: postly
description: "A new Flutter project."
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.5.2
dependencies:
flutter:
sdk: flutter
cherrypick: ^2.2.0-dev.1
cherrypick_annotations: ^1.1.0-dev.0
dio: ^5.4.0
retrofit: ^4.0.3
freezed_annotation: ^2.3.2
dartz: ^0.10.1
flutter_bloc: ^9.1.1
auto_route: ^9.3.0+1
cupertino_icons: ^1.0.8
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
cherrypick_generator: ^1.1.0-dev.1
build_runner: 2.4.13
retrofit_generator: ^9.1.5
freezed: ^2.3.2
json_serializable: ^6.9.0
auto_route_generator: ^9.0.0
flutter:
uses-material-design: true

View File

@@ -0,0 +1,41 @@
// 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:cherrypick/cherrypick.dart';
//import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:postly/di/app_module.dart';
//import 'package:postly/main.dart';
void main() {
late Scope scope;
setUp(() {
scope = CherryPick.openRootScope();
scope.installModules([$AppModule()]);
});
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
expect(1, 1);
// Build our app and trigger a frame.
//await tester.pumpWidget(MyApp(
// scope: scope,
//));
//// 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.

After

Width:  |  Height:  |  Size: 917 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@@ -0,0 +1,38 @@
<!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="postly">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>postly</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<script src="flutter_bootstrap.js" async></script>
</body>
</html>

View File

@@ -0,0 +1,35 @@
{
"name": "postly",
"short_name": "postly",
"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"
}
]
}

View File

@@ -5,11 +5,30 @@ sdkPath: .fvm/flutter_sdk
packages: packages:
- cherrypick - cherrypick
- cherrypick_flutter - cherrypick_flutter
- cherrypick_annotations
- cherrypick_generator
- examples/client_app
- examples/postly
scripts: scripts:
analyze: analyze:
run: | exec: dart analyze
flutter analyze
format: format:
exec: dart format lib
test:
exec: flutter test
codegen:
run: | run: |
flutter format melos exec --scope="postly" -- dart run build_runner build --delete-conflicting-outputs
outdated:
exec: dart pub outdated
upgrade:
exec: dart pub upgrade --major-versions
drop:
exec: flutter clean

View File

@@ -623,4 +623,4 @@ packages:
source: hosted source: hosted
version: "2.2.2" version: "2.2.2"
sdks: sdks:
dart: ">=3.5.0 <4.0.0" dart: ">=3.5.2 <4.0.0"

View File

@@ -7,7 +7,7 @@ repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
environment: environment:
sdk: ">=3.0.0 <4.0.0" sdk: ">=3.5.2 <4.0.0"
dependencies: dependencies:
meta: ^1.3.0 meta: ^1.3.0