cleany 2.0.7
cleany: ^2.0.7 copied to clipboard
Interactive Flutter architecture CLI for features, components and use cases, with Cubit or Bloc, safe generation, environment configuration and encrypted local storage.
Cleany #
Build your Flutter features with a structure your team can follow.
Cleany is an interactive CLI that generates Feature-Based + Clean Architecture projects using Cubit or Bloc, Freezed, and multiple_result. It prepares the app foundation, creates features and reusable components, and connects their dependencies and routes.
Run cleany, choose an action, review the changes, and apply. The generated code lives in your project, ready for your API and business logic.
Get started · CLI commands · Architecture · Run your app · Storage · Localization
Why use Cleany? #
A new feature usually means creating the same layers, state classes, dependency registrations, and routes. Cleany handles that setup consistently, so you can spend your time implementing the feature.
Features #
- A shared starting point: one fixed architecture makes features easier to navigate, review, and maintain as a team.
- Choose your state management: select Cubit or Bloc for each feature, with immutable Freezed states and separate progress for each use case.
- Keep work inside its feature: API clients, repositories, use cases, dependency registrations, and routes have clear homes.
- Reuse smaller pieces: components can own local Cubit/Bloc state without becoming pages or full features.
- Start with the essentials: Dio or Retrofit, Arabic/English localization, responsive Sizer themes, encrypted storage, and dev/UAT/prod configuration.
- Review before applying: generation uses an isolated workspace, validation, tracked file ownership, and recoverable updates.
- Maintain the project: manage entries, add use cases, repair supported issues, recover interrupted operations, and run common build recipes from the menu.
Cleany scaffolds the application. You define its backend contracts, business rules, and finished UI.
Get started #
Use a Flutter SDK on PATH with Dart 3.13 or newer within Dart 3.x. The CLI runs on macOS, Linux, and Windows.
Install the published package:
dart pub global activate cleany
Or activate this checkout from the Cleany repository:
dart pub global activate --source path .
Create a Flutter project and open Cleany:
flutter create playground
cd playground
cleany
- Choose 11 — Initialize project. Confirm the app identity, select an API provider, and enter the environment URLs.
- Choose 1 — Create feature. Enter
home, select Cubit or Bloc, and choose its location and response fields. - Review the planned files and select Apply and validate.
- Connect the generated Data layer to your API, then run the app.
If cleany is not found, add your pub-cache bin directory to PATH or use dart pub global run cleany:cleany. After updating a local installation, restart your Cleany session.
Cleany presents #
The header shows your project name, installed Cleany version, initialization status, and registered entry counts. For example, after creating a feature and a component:
╭────────────────────────────────────────────────────────╮
CLEANY v2.0.7 · Project: playground
Status: Initialized │ Features: 1 │ Components: 1
╰────────────────────────────────────────────────────────╯
[ Generation ]
1. Create feature
2. Create component
3. Add use case
4. Create shared service
[ Cleanup ]
5. Remove feature
6. Remove component
[ Inspection & Management ]
7. List and manage features
8. List and manage components
9. Rename an entry
10. Move an entry
[ Core & Setup ]
11. Initialize project (Disabled: Project is already initialized)
12. Configure native flavors
13. Add AppConfig value
[ Maintenance & Scripts ]
14. Self-healing doctor & recovery
15. Run build runner / Flutter scripts
0. Exit
› Choose a number or use arrows:
Finding your way around:
- Type a number, or use arrows and Enter in a supported terminal. Arabic/Persian digits also work.
- Unavailable options are dimmed and explain what is missing. New projects highlight 11; detected problems or interrupted operations highlight 14.
- During a wizard, use Ctrl+B, Page Up, Alt+Left, or
:backto return to the previous input. Previous answers remain available as defaults. - Use Esc, Ctrl+C, or
:cancelto cancel. During execution, cancellation requests command termination and safe rollback. - After an action, the compact header keeps results visible. Type m or M to display the full menu again.
Names are normalized automatically: UserProfile becomes user_profile, and an AppConfig key such as supportEmail becomes SUPPORT_EMAIL. Values and JSON keys retain their case. Invalid names and collisions are rejected.
Source changes finish with exactly two review choices:
1. Apply and validate
2. Cancel
› Continue [2]:
Enter defaults to Cancel. Run Cleany without flags or subcommands; its actions live in the menu.
Generated architecture #
This example uses a home feature with Cubit and Retrofit, plus a stateful user_card component:
playground/
├── android/ # Native folders created by Flutter
├── ios/
├── assets/
│ ├── images/
│ ├── icons/
│ └── translations/
│ ├── app_en.arb
│ └── app_ar.arb
├── config/flavors/
│ ├── dev.yaml
│ ├── uat.yaml
│ └── prod.yaml
├── lib/
│ ├── app/
│ │ ├── app.dart
│ │ ├── bootstrap.dart
│ │ ├── application_root.dart
│ │ ├── application_lifetime.dart
│ │ ├── config/
│ │ │ ├── app_config.dart
│ │ │ ├── app_environment.dart
│ │ │ └── flavor_config.dart
│ │ ├── di/injection.dart
│ │ ├── router/app_router.dart
│ │ ├── services/
│ │ │ ├── app_settings_manager.dart
│ │ │ ├── user_session_manager.dart
│ │ │ ├── service_providers.dart
│ │ │ ├── entities/user_session_entity.dart
│ │ │ └── service_extension/session_data_exception.dart
│ │ └── startup/
│ │ ├── startup_stage.dart
│ │ └── startup_failure_app.dart
│ ├── core/
│ │ ├── network/
│ │ │ ├── failure_mapper.dart
│ │ │ └── dio/
│ │ │ ├── dio_client.dart
│ │ │ └── interceptors/auth_interceptor.dart
│ │ ├── errors/
│ │ ├── observers/my_bloc_observer.dart
│ │ ├── state/use_case_state.dart
│ │ ├── storage/
│ │ │ ├── local_storage.dart
│ │ │ ├── app_local_storage.dart
│ │ │ ├── local_keys.dart
│ │ │ └── storage_extension/ # Initialization, key policies, cipher, adapters
│ │ ├── localization/generated/
│ │ ├── theme/
│ │ │ ├── app_colors.dart
│ │ │ ├── app_text_theme.dart
│ │ │ └── app_theme.dart
│ │ ├── constants/
│ │ ├── utils/
│ │ └── widgets/
│ ├── features/home/
│ │ ├── di/home_dependencies.dart
│ │ ├── routing/home_routes.dart
│ │ ├── data/
│ │ │ ├── api/home_api.dart
│ │ │ ├── datasources/home_remote_data_source.dart
│ │ │ ├── models/home_model.dart
│ │ │ └── repositories/home_repository_impl.dart
│ │ ├── domain/
│ │ │ ├── entities/home_entity.dart
│ │ │ ├── repositories/home_repository.dart
│ │ │ └── usecases/get_home.dart
│ │ └── presentation/
│ │ ├── cubit/
│ │ │ ├── home_cubit.dart
│ │ │ └── home_state.dart
│ │ ├── pages/home_page.dart
│ │ └── widgets/
│ ├── components/user_card/
│ │ ├── cubit/
│ │ │ ├── user_card_cubit.dart
│ │ │ └── user_card_state.dart
│ │ └── user_card_widget.dart
│ ├── main.dart
│ ├── main_dev.dart
│ ├── main_uat.dart
│ └── main_prod.dart
├── test/
├── integration_test/
├── .cleany/features.json
├── .vscode/launch.json
├── flavorizr.yaml
├── l10n.yaml
├── analysis_options.yaml
└── pubspec.yaml
Bloc features use a bloc/ directory with event, state, and controller files. Direct Dio features omit the Retrofit API client. Freezed/JSON outputs are generated beside their sources during validation.
API paths live in the feature's API client or datasource; no central api_endpoints.dart placeholder is generated.
Each feature's route file owns its paths and private page/BlocProvider composition. The app router includes ...HomeRoutes.build(container). New projects use this single-file approach without RouteNames, FeaturePages, or a separate home_pages.dart.
Data flow and ownership #
API response (JSON)
→ DataSource
→ Repository: JSON → Model → Entity, or Exception → Failure
→ Result<Entity, Failure>
→ Use case
→ Cubit or Bloc: UseCaseState<T>
→ UI
Datasources return raw JSON. Repositories handle decoding, Entity mapping, and technical failures. Domain contains Entities, repository contracts, and use cases; it stays independent of Flutter widgets and network libraries. Presentation works with Entities and typed operation state.
A feature has one Freezed State with a primary status such as homeStatus. Each added use case gets its own status, such as refreshHomeStatus, so loading one operation preserves the others. UI renders initial, loading, success, and failure through state.homeStatus.when(...).
| Resource | Lifetime and owner |
|---|---|
| AppConfig, storage, shared managers | App-scoped; widgets borrow the same instances through providers |
| Dio, feature repositories, use cases | Registered in GetIt; feature registrations live in the feature's DI module |
| Feature Cubit/Bloc | Factory-created; its page BlocProvider closes it |
| Component Cubit/Bloc | Created and closed by that component's local BlocProvider |
bootstrap.dart prepares services and the router. application_root.dart connects providers, theme, and locale. application_lifetime.dart disposes app resources. Pass dependencies into controllers and Data classes through constructors; use context.read at the UI boundary.
CLI commands #
1 — Create feature #
Create the Data, Domain, and Presentation layers, then connect DI and routing automatically.
Name (snake_case): home
State management: 1 # Cubit; 2 selects Bloc
Location [1]: 1 # Default directory
Data contract [1]: 2 # Define fields and API contract
Response field count (1 to 30): 2
Response field 1, lowerCamelCase:type:JSON key: userName:string:user_name
Nullable [1] (y/N): n
Response field 2, lowerCamelCase:type:JSON key: age:int:age
Nullable [2] (y/N): y
Continue [2]: 1
Choose a default directory, a custom parent inside lib, or an existing feature. For example, the custom parent lib/modules/account and name profile produce lib/modules/account/profile.
Use default id fields or define up to 30 fields as name:type:jsonKey. Supported types: string, int, double, bool, datetime, list, list<string>, list<int>, list<num>, list<map<string,dynamic>>, map<string,dynamic>, set, and dynamic.
The wizard collects response fields. The initial API scaffold uses GET; update the feature's API client or datasource to match your endpoint and response.
2 — Create component #
Create a reusable widget with Cubit, Bloc, or no state management. The wizard asks for its name and location; it does not ask for response fields.
For user_card, the widget is lib/components/user_card/user_card_widget.dart, with optional cubit/ or bloc/ files beside it. Embed const UserCardWidget() in feature UI.
Stateful components own their BlocProvider and controller. They have no route, central page factory, or GetIt controller registration; separate instances keep separate state.
3 — Add use case #
Select an existing feature, enter an operation name such as refresh_home, and choose void, the feature's Entity, List, or advanced typed input. For an Entity result, keep the suggested type or select another existing Domain Entity.
Cleany adds the Domain use case, extends the existing repository and Data implementation, registers the dependency, and connects the feature's Cubit/Bloc. The existing Model and Entity remain available for mapping.
Call it from a UI callback:
// Cubit feature:
context.read<HomeCubit>().refreshHome();
// Bloc feature:
context.read<HomeBloc>().add(const HomeEvent.refreshHomeRequested());
Observe state.refreshHomeStatus for its result. The new Data connection returns Failure until you implement it. Cleany does not guess an HTTP method or endpoint. Update custom repository implementations and test fakes when their contract gains a method.
4 — Create shared service #
Enter a name such as AnalyticsManager. Cleany creates an empty class at lib/app/services/analytics_manager.dart, registers a lazy app-scoped GetIt singleton, and exposes that instance to UI providers.
Add your service behavior, then read it with context.read<AnalyticsManager>() in UI or inject it through a constructor into another service.
5 — Remove feature #
Select a feature and review removal of its directory, registered descendants, and owned DI/router integrations. Deletion includes custom edits inside the selected folders. External files require recorded ownership; matching a name alone does not authorize removal.
6 — Remove component #
Select a component and review removal of its folder and owned integrations. This also removes custom files inside that folder. Remaining references must pass staged validation before changes apply.
7 — List and manage features #
View registered features with their state-management style and location. Select one to add a use case, rename, move, or remove it directly. Main-menu option 3 remains available for independent use-case generation.
8 — List and manage components #
View and select registered components, then rename, move, or remove the selected item. Choose 0 to return to the main menu.
9 — Rename an entry #
Select a feature or component and enter its new name. Cleany updates supported symbols, owned filenames, imports, DI, routes, and registry metadata while keeping the parent directory. Customized route paths and backend endpoints are preserved.
10 — Move an entry #
Select an entry and enter a new parent inside lib, such as lib/modules. Its name stays the same; supported references and registry paths move with it. Dynamic or unsupported references may need manual updates.
11 — Initialize project #
Prepare the app foundation: startup, DI, networking, storage, themes, localization, environment files, and run profiles.
Cleany detects supported production app identities, or asks you to select/enter one. For com.example.playground, it prepares:
| Environment | App identity |
|---|---|
| prod | com.example.playground |
| dev | com.example.playground.dev |
| uat | com.example.playground.uat |
Choose Retrofit over Dio or Dio, then enter the three API base URLs. Leaving a URL blank uses http://localhost:80 for dev and https://localhost:80 for uat/prod. These are placeholders; replace them with your backend. Dev accepts HTTP or HTTPS. UAT/prod require HTTPS for every host, including localhost.
Initialization protects existing app/core directories. In older projects, update HTTP UAT/prod URLs to HTTPS before generation; Cleany does not guess a secure address for your backend. Use Doctor for supported repairs to an initialized project. Native flavor configuration is a separate step under option 12.
12 — Configure native flavors #
Select an existing Android, iOS, or macOS platform, or all available platforms. Cleany runs the configured Flutter Flavorizr processors in staging and reviews native file changes before applying them.
Have the required platform toolchain installed. Use this step before launching with --flavor dev, --flavor uat, or --flavor prod.
13 — Add AppConfig value #
Enter a public configuration key and its values for dev, uat, and prod:
Key (UPPER_SNAKE_CASE): SENTRY_DSN
dev value: YOUR_DEV_DSN
uat value: YOUR_UAT_DSN
prod value: YOUR_PROD_DSN
Continue [2]: 1
Cleany adds sentry_dsn to each flavor YAML, a typed sentryDsn property to AppConfig, and a String.fromEnvironment('SENTRY_DSN') override.
Read it in a widget with context.read<AppConfig>().sentryDsn. The command adds configuration; installing and initializing an SDK remains application code. Custom String defines override YAML, including explicitly empty values.
14 — Self-healing doctor & recovery #
Use this when project metadata, generated files, or supported integrations need attention. Interrupted transactions are reviewed for recovery first; safe files are restored while conflicting edits and backups remain available.
| Submenu | What it does |
|---|---|
| 1 — Inspect, repair and rebuild | Inspect registry, files, dependencies, DI and routes; review supported repairs; regenerate code and analyze |
| 2 — Clean abandoned Cleany cache | Clean owned local workspaces while preserving source, recovery data, and global package caches |
| 3 — Set command timeout | Set a per-command limit from 5–3600 seconds; default 300 |
| 0 — Return | Go back without applying changes |
Missing builder outputs are regenerated. Damaged, registry-owned generated files require explicit cleanup approval, then the normal final review. Original bytes are archived, and a successful rebuild must restore those outputs before commit.
Doctor preserves customized source and healthy features. Arbitrary Dart errors or unsupported custom integrations need developer fixes. There is no architecture reset in this menu.
Deleting a feature directory manually leaves stale registrations. Doctor uses the registry and generated layout markers to remove only verified bindings, including when the last feature is gone; it does not require legacy FeaturePages files in modern projects. Invalid recorded Dart source reports its file, line, column, and parser message before any repairs apply.
After editing an Entity or Model and running build_runner yourself, changed owned outputs are checked against a clean rebuild in staging. An exact match refreshes their source/output fingerprints without repeated “custom output” warnings. A mismatch preserves the originals and stops the operation with the affected path; generated comments alone never authorize replacement.
15 — Run build runner / Flutter scripts #
Choose a fixed recipe, review its commands, then apply. Each sequence stops at the first failure.
1. Dependencies & Clean — Standard setup
flutter clean
flutter pub get
dart run build_runner build --delete-conflicting-outputs
flutter gen-l10n
dart format .
2. Build & Code Generation — Rebuild outputs
dart run build_runner clean
dart run build_runner build
dart run build_runner build --delete-conflicting-outputs
dart format .
3. Cache & Storage Cleanup — Clean build caches
Clear the reviewed project build/, .dart_tool/, and lockfile, resolving a fresh pubspec.lock. The recipe runs:
flutter clean
flutter pub get
dart run build_runner clean
flutter pub cache repair
4. Automation — Run to fix issue
Run recipe 3, followed by:
flutter pub get
dart run build_runner build
flutter gen-l10n
dart run build_runner build --delete-conflicting-outputs
dart format .
Choose 0 to return. Recipes explain missing prerequisites. Project commands run in staging; reviewed project caches are cleared at commit with recovery protection. Formatting may change layout while authored source logic remains protected.
Recipes 3 and 4 also repair the shared Dart package cache, outside the project transaction; that global effect cannot be rolled back. Fresh lockfile resolution may change dependency versions within your constraints. Application storage and sessions are not deleted.
0 — Exit #
Close the session. An incomplete, unapplied form is cancelled; previously completed operations remain applied.
Run the generated application #
Set the API URL and storage key in config/flavors/<environment>.yaml, then choose an entrypoint:
flutter run --target lib/main_dev.dart
flutter run --target lib/main_uat.dart
flutter run --target lib/main_prod.dart --release
Override configuration for a particular run:
flutter run --target lib/main_dev.dart \
--dart-define=API_BASE_URL=https://api.example.com \
--dart-define=DB_SECRET_KEY=YOUR_STORAGE_PASSPHRASE \
--dart-define=SENTRY_DSN=YOUR_DEV_DSN
Use the exact key registered through option 13. Rerun/rebuild after changing defines; hot reload does not change compile-time values. Explicitly empty API or storage-key overrides fail validation.
After option 12 configures the platform, select the native flavor too:
flutter run --flavor dev --target lib/main_dev.dart
flutter build appbundle --flavor prod --target lib/main_prod.dart --release
VS Code profiles are generated in .vscode/launch.json; select Cleany DEV, Cleany UAT, or Cleany PROD. Recognizable Flutter scaffold entrypoints delegate to dev. Unused default widgets such as MainApp are removed after archiving the original; widgets referenced by project code/tests and custom startup code are preserved. The generated CLEANY_RUN.md explains the profiles.
context.read<AppConfig>() gives pages the same immutable configuration used by DI. Its isDebug property follows Flutter's build mode: true in Debug and false in Profile/Release, regardless of the selected environment. Startup configuration/service failures show a recovery screen. MyBlocObserver traces Cubit/Bloc lifecycle and state changes in Debug only.
Encrypted local storage #
Initialization provides an app-scoped AppLocalStorage, backed by Sembast, behind the LocalStorage interface. Data services and shared managers receive that interface through constructors; widgets can read it from context.
Add application keys to lib/core/storage/local_keys.dart:
static const lastSearch = 'last_search';
Then use storage inside an async UI action. Replace playground with your package name:
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:playground/core/storage/local_storage.dart';
import 'package:playground/core/storage/local_keys.dart';
final storage = context.read<LocalStorage>();
await storage.put(key: LocalKeys.lastSearch, value: 'Headphones');
final query = await storage.get<String>(key: LocalKeys.lastSearch);
final exists = await storage.containsKey(key: LocalKeys.lastSearch);
await storage.remove(key: LocalKeys.lastSearch);
get<T> returns null for a missing value or type mismatch. Use its optional decoder for typed collections. clear() removes all stored records; DI owns close(), so UI consumers leave disposal to the app. Authentication failures throw instead of looking like missing data.
Values use AES-256-GCM authentication/encryption; logical key names use HMAC. Password mode derives a key with a random persisted salt. The storage key is resolved in this order:
DB_SECRET_KEYdart-define.- An explicit startup key:
bootstrap(AppEnvironment.dev, dbSecretKey: runtimeSecret). db_secret_keyin the selected flavor YAML.
Dart contains no fallback password. Missing/empty keys fail before storage opens. New flavor YAML sets db_secret_key: "auto": storage creates a random 256-bit key per app/environment and keeps it in platform secure storage.
To choose password mode before first use, replace auto in the flavor YAML or pass --dart-define=DB_SECRET_KEY=your-passphrase when running Flutter. YAML and dart-defines are extractable client configuration, so bundled passphrases are not hidden secrets. VaultKey, PassphraseKey, and RawKey are supported in custom storage composition.
Doctor preserves existing configured keys. Changing an existing database's key policy/password requires a deliberate data migration; wrong or lost keys never trigger a silent database reset. Follow LOCAL_STORAGE.md for platform-vault setup and backup/recovery requirements before release.
AppSettingsManager persists theme/language preferences. UserSessionManager persists typed session data. Their successful storage writes update memory and notify listeners; clearing a session preserves other settings.
Localization #
New projects include English and Arabic through Flutter's official flutter_localizations and gen-l10n, with Arabic RTL layout.
- Add matching message keys to
assets/translations/app_en.arbandapp_ar.arb. - Run
flutter gen-l10nto updatelib/core/localization/generated/. - Import
app_localizations.dartand read messages withAppLocalizations.of(context).welcome.
Generated pages and failure messages use localization keys. Add your own translations for application-specific copy.
To change the language from a UI action, import AppSettingsManager and flutter_bloc, then call:
await context.read<AppSettingsManager>().setLanguage('ar');
The app rebuilds with the selected locale and persists it. Settings start with English and the system theme; setThemeMode('light'), 'dark', or 'system' updates the theme similarly.
Working safely #
Generation plans are validated in staging before source files are applied. Input/output checks and a recovery journal protect supported changes; multi-file application is recoverable rather than one indivisible filesystem operation. Commit .cleany/features.json with your source: it records entry contracts, paths, ownership, and template profiles.
Errors show Cause, Suggested fix, and Log file. Failed actions offer retry with retained inputs and a fresh review. Existing custom code is preserved where supported; unsupported structures require manual integration. Doctor restores recorded layouts instead of silently migrating older projects.
Changelog · Detailed usage guide · Report an issue · BSD 3-Clause license