flutter_feature_generator 2.2.0 copy "flutter_feature_generator: ^2.2.0" to clipboard
flutter_feature_generator: ^2.2.0 copied to clipboard

A powerful code generator with web interface for creating clean architecture features in Flutter projects from OpenAPI/Swagger specifications.

Flutter Feature Generator #

A powerful code generator with interactive web interface for creating clean architecture features in Flutter projects from OpenAPI/Swagger specifications.

Web Interface

✨ What's New in v2.0.0 #

🌐 Interactive Web Interface: Beautiful, modern web UI for selecting APIs and configuring generation 📤 File Upload Support: Upload swagger files directly in the browser - no need to have it in project root 🎛️ Granular Layer Control: Choose exactly which layers to generate (Data, Domain, Presentation) 🧩 Presentation Components: Fine-grained control over BLoC, Screens, and Widgets 🔄 Smart Appending: Automatically appends to existing features instead of overwriting 📝 Consolidated Classes: Adds methods to existing classes instead of creating separate ones 🎯 Real-time Search: Filter APIs by path, method, tag, or description ✅ Multi-Selection: Select multiple endpoints with visual feedback

Features #

  • 🌐 Modern Web Interface: Interactive UI for API selection and configuration
  • 📤 File Upload: Upload swagger files directly in the browser - works with or without a local file
  • 🏗️ Clean Architecture: Generates complete feature structure following clean architecture principles
  • 📄 Swagger Integration: Automatically parses OpenAPI/Swagger specifications
  • 📦 Smart Core Files: Optional generation of shared core files (Error class) with existence detection
  • 🎛️ Granular Control: Choose specific layers and components to generate
  • 🔄 Smart Appending: Add new APIs to existing features without overwriting
  • 🎯 Interactive Selection: Multi-select APIs with search and filtering
  • 📁 Flexible Structure: Configurable project structure and paths
  • 🔒 Name Validation: Prevents conflicts with reserved folder names
  • 📱 Responsive Design: Works on desktop and mobile browsers

Installation #

dart pub global activate flutter_feature_generator

Local Installation #

Add to your pubspec.yaml:

dev_dependencies:
  flutter_feature_generator: ^2.0.0

Then run:

dart pub get

Usage #

Web Interface (New!) #

Start the interactive web interface:

# Run in your Flutter project root
flutter_feature_generator

# Or explicitly start web mode
flutter_feature_generator --web

Then open your browser and navigate to: http://localhost:8080

Web Interface Features:

  • 🔍 Search & Filter: Find APIs by path, method, tag, or description
  • Multi-Selection: Click to select/deselect multiple endpoints
  • 📦 Core Files Control: Choose which core files to generate (Error class, etc.)
  • 🎛️ Layer Control: Choose which layers to generate:
    • Data Layer: Models, Services, Repository Implementation
    • Domain Layer: Use Cases, Repository Interface
    • Presentation Layer: BLoC, Screens, Widgets (individually selectable)
  • 📝 Smart Validation: Real-time feature name validation
  • 🎯 Visual Feedback: Clear status messages and progress indicators
  • Smart Detection: Shows which core files already exist

Command Line Interface #

For automation and scripting, you can still use the CLI:

# Show available endpoints and usage
flutter_feature_generator

# Generate feature with specific endpoints
flutter_feature_generator user_management 1,3,5

# Generate all endpoints
flutter_feature_generator api_features all

Layer Selection #

Choose exactly what you need:

Full Stack

  • ✅ Data Layer
  • ✅ Domain Layer
  • ✅ Presentation Layer (BLoC + Screens + Widgets)

Backend Only

  • ✅ Data Layer
  • ✅ Domain Layer
  • ❌ Presentation Layer

Business Logic Only

  • ❌ Data Layer
  • ✅ Domain Layer
  • ✅ Presentation Layer (BLoC only)

UI Only

  • ❌ Data Layer
  • ❌ Domain Layer
  • ✅ Presentation Layer (Screens + Widgets only)

Project Structure #

The generator creates features following this clean architecture structure:

lib/features/your_feature/
├── data/                          # Data Layer
│   ├── model/
│   │   ├── request_model.dart
│   │   └── response_model.dart
│   ├── remote/
│   │   ├── service/
│   │   │   └── your_feature_service.dart      # Retrofit API calls
│   │   └── source/
│   │       ├── your_feature_source.dart       # Data source interface
│   │       └── your_feature_source_impl.dart  # Data source implementation
│   └── repository/
│       └── your_feature_repository_impl.dart  # Repository implementation
├── domain/                        # Domain Layer
│   ├── repository/
│   │   └── your_feature_repository.dart       # Repository interface
│   └── usecase/
│       └── your_feature_usecase.dart          # Business logic
└── presentation/                  # Presentation Layer
    ├── bloc/                      # State Management
    │   ├── your_feature_bloc.dart
    │   ├── your_feature_event.dart
    │   └── your_feature_state.dart
    ├── screen/                    # UI Screens
    │   └── your_feature_screen.dart
    └── widget/                    # Custom Widgets

Smart Appending #

When you add new APIs to an existing feature, the generator intelligently:

  • Adds methods to existing UseCases class
  • Adds factory methods to existing freezed Event class
  • Adds fields to existing freezed State class
  • Adds handlers to existing BLoC class
  • Adds methods to Repository interface and implementation
  • Adds methods to Source interface and implementation
  • Adds endpoints to Service class
  • Generates missing models only
  • Never overwrites existing code

Requirements #

  • Dart SDK: >=3.0.0 <4.0.0
  • A swagger.json or OpenAPI specification file (can be in project root or uploaded via web interface)
  • Flutter project with standard structure

Swagger File Options #

You have two ways to provide your OpenAPI/Swagger specification:

  1. Default file in project root (Recommended for development):

    • Place swagger.json in your project root directory
    • The generator will automatically detect and load it on startup
  2. Upload via web interface (Recommended for flexibility):

    • Start the web interface without a swagger file in the root
    • Click "Choose Swagger File" to upload your swagger.json
    • Change the file anytime using the "Change File" button
    • Perfect for testing different API specifications

Required Dependencies #

The generated code uses several packages that must be added to your Flutter project:

dependencies:
  # Error handling with functional programming
  dartz: ^0.10.1
  
  # Dependency injection
  injectable: ^2.3.2
  get_it: ^7.6.4
  
  # Code generation for models and state management
  freezed_annotation: ^2.4.1
  json_annotation: ^4.8.1
  
  # HTTP client for API calls
  retrofit: ^4.0.3
  dio: ^5.3.2

dev_dependencies:
  # Code generation tools
  build_runner: ^2.4.7
  freezed: ^2.4.6
  json_serializable: ^6.7.1
  retrofit_generator: ^8.0.4
  injectable_generator: ^2.4.1

Package Explanations:

  • 🎯 dartz: Provides Either<Error, T> for functional error handling in use cases and repositories
  • 💉 injectable & get_it: Dependency injection for clean architecture - register your repositories and use cases
  • 🧊 freezed: Generates immutable classes for models, events, and states with unions and pattern matching
  • 🌐 retrofit & dio: HTTP client generation from your service interfaces - handles API calls automatically
  • 🔧 json_annotation & json_serializable: Generates fromJson and toJson methods for your models
  • ⚙️ build_runner: Runs code generation for all the above packages

Quick Setup #

Add the dependencies to your pubspec.yaml, then run:

# Install dependencies
flutter pub get

# Generate code (run this after generating features)
dart run build_runner build

# For development (watches for changes)
dart run build_runner watch

Configuration #

Swagger/OpenAPI File #

Place your API specification file (swagger.json or openapi.yaml) in your project root. The web interface will automatically load and parse it.

Feature Naming #

Feature names must follow snake_case format (e.g., user_management, chat_system).

Restricted Names (to prevent conflicts):

  • test, build, lib
  • android, ios, web, windows, linux, macos

Examples #

Web Interface Workflow #

  1. Start the server:

    flutter_feature_generator
    
  2. Open browser: Navigate to http://localhost:8080

  3. Upload swagger file (if not in project root):

    • Click "Choose Swagger File" button
    • Select your swagger.json file
    • The file will be loaded and endpoints will appear
  4. Select APIs: Use search and multi-select to choose endpoints

  5. Set feature name: Enter a snake_case name (e.g., user_profile)

  6. Configure core files:

    • Check "Error Class" to generate shared error handling
    • Shows "✓ Exists" if already present (won't regenerate)
  7. Configure layers: Select which components to generate

    • Data Layer, Domain Layer, Presentation Layer
    • Fine-tune Presentation components (BLoC, Screens, Widgets)
  8. Generate: Click "Generate Feature" and see real-time progress

CLI Workflow #

  1. Show available APIs:

    flutter_feature_generator
    
  2. Generate specific endpoints:

    flutter_feature_generator user_management 1,3,5,7
    
  3. Generate all endpoints:

    flutter_feature_generator complete_api all
    

Generated Files Integration #

After generation, complete the integration:

  1. Add required dependencies (see Requirements section above)

  2. Generate build files:

    dart run build_runner build
    

    This generates:

    • .freezed.dart files for models, events, and states
    • .g.dart files for JSON serialization
    • .config.dart files for dependency injection
  3. Configure dependency injection in your main.dart:

    @InjectableInit()
    void configureDependencies() => GetIt.instance.init();
       
    void main() {
      configureDependencies();
      runApp(MyApp());
    }
    
  4. Register your repositories in a DI module:

    @module
    abstract class AppModule {
      @injectable
      UserManagementRepository userRepo(UserManagementRepositoryImpl impl) => impl;
    }
    
  5. Use in your app: Import and use the generated components

Example BLoC usage:

BlocProvider(
  create: (context) => UserManagementBloc(
    GetIt.instance<UserManagementUseCases>(),
  ),
  child: UserManagementScreen(),
)

🎯 Core Files Generation #

The generator can create shared core files used across all features:

Error Class (lib/core/error/error.dart)

A comprehensive error handling class with freezed unions for functional error handling:

  • Smart Generation: Only generates if the file doesn't already exist
  • Web Interface Control: Checkbox option in the "Core Files" section
  • CLI Behavior: Automatically generated when using CLI mode
  • Existence Detection: UI shows "✓ Exists" indicator if already present
// Generated error class with multiple error types
@freezed
class Error with _$Error {
  const factory Error.httpInternalServerError(String errorBody) = HttpInternalServerError;
  const factory Error.httpUnAuthorizedError() = HttpUnAuthorizedError;
  const factory Error.httpUnknownError(String message) = HttpUnknownError;
  const factory Error.firebaseAuthError(String message) = FirebaseAuthError;
  const factory Error.auth0AuthError(String message) = Auth0AuthError;
  const factory Error.customErrorType(String message) = CustomErrorType;
  const factory Error.fileNotFoundError(String filePath) = FileNotFoundError;
  const factory Error.decryptionFailed(String message) = DecryptionFailedError;
  const factory Error.fileAlreadyExists(String filePath) = FileAlreadyExistsError;
  const factory Error.none() = NoError;
}

// Usage in your code with functional error handling
result.fold(
  (error) => error.when(
    httpUnAuthorizedError: () => handleUnauthorized(),
    httpUnknownError: (message) => showError(message),
    // ... handle other error cases
  ),
  (data) => handleSuccess(data),
);

Benefits:

  • Type-safe error handling: Compile-time guarantees for all error cases
  • Functional programming: Works with dartz's Either<Error, T> type
  • Pattern matching: Exhaustive error handling with freezed unions
  • Reusable: Shared across all generated features

Contributing #

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog #

See CHANGELOG.md for a list of changes in each version.


Made with ❤️ for the Flutter community

5
likes
150
points
37
downloads

Publisher

unverified uploader

Weekly Downloads

A powerful code generator with web interface for creating clean architecture features in Flutter projects from OpenAPI/Swagger specifications.

Homepage
Repository (GitHub)
View/report issues

Documentation

Documentation
API reference

License

MIT (license)

Dependencies

args, path, shelf, shelf_router

More

Packages that depend on flutter_feature_generator