bashar-shaeb/laravel-flutter-generator

A Laravel package that bridges Laravel backend with Flutter frontend by generating complete Flutter features (models, services, UI components) from Laravel models and routes

dev-main 2025-05-24 10:06 UTC

This package is auto-updated.

Last update: 2025-05-24 10:06:33 UTC


README

A comprehensive Laravel package that bridges your Laravel backend with Flutter frontend by automatically generating complete Flutter features (models, services, UI components) from your existing Laravel Eloquent models and routes.

Features

  • ๐Ÿš€ Automatic Code Generation: Generate complete Flutter features from Laravel models
  • ๐Ÿ“ฑ UI Components: Create forms, lists, and detail views automatically
  • ๐Ÿ”— API Integration: Generate Flutter services that integrate with Laravel API endpoints
  • ๐Ÿ—๏ธ SOLID Principles: Clean, maintainable code following best practices
  • ๐ŸŽจ Customizable Templates: Modify generation templates to fit your needs
  • ๐Ÿงช Comprehensive Testing: Full test coverage for reliable code generation
  • ๐Ÿ”„ CRUD Operations: Complete Create, Read, Update, Delete functionality
  • ๐ŸŽฏ Type Safety: Full Dart null safety support
  • ๐Ÿ“Š Relationship Support: Handle Eloquent model relationships
  • โšก Performance Optimized: Efficient code generation with minimal dependencies

Installation

Install the package via Composer:

composer require bashar-shaeb/laravel-flutter-generator

Publish the configuration file:

php artisan vendor:publish --provider="BasharShaeb\LaravelFlutterGenerator\FlutterGeneratorServiceProvider" --tag="flutter-generator-config"

Optionally, publish the templates for customization:

php artisan vendor:publish --provider="BasharShaeb\LaravelFlutterGenerator\FlutterGeneratorServiceProvider" --tag="flutter-generator-templates"

Quick Start

1. Generate a Dart model from Laravel model:

php artisan flutter:generate-model User

2. Generate API service for a model:

php artisan flutter:generate-service User --with-routes

3. Generate complete feature (model + service + UI):

php artisan flutter:generate-feature User

4. Generate everything for all models:

php artisan flutter:generate-all

5. Generate for specific models only:

php artisan flutter:generate-all --models=User,Post,Category

Command Options

Global Options

  • --force: Overwrite existing files without confirmation
  • --all: Process all available models

Feature-specific Options

  • --skip-model: Skip model generation
  • --skip-service: Skip service generation
  • --skip-widgets: Skip widget generation
  • --skip-screens: Skip screen generation
  • --with-routes: Include route analysis for custom API methods

Configuration

The package configuration file is published to config/flutter-generator.php. Key configuration options:

Output Paths

'output' => [
    'base_path' => base_path('flutter_output'),
    'models_path' => 'models',
    'services_path' => 'services',
    'widgets_path' => 'widgets',
    'screens_path' => 'screens',
],

API Configuration

'api' => [
    'base_url' => env('FLUTTER_API_BASE_URL', 'http://localhost:8000/api'),
    'timeout' => 30,
    'authentication' => [
        'type' => 'bearer', // bearer, basic, none
        'header_name' => 'Authorization',
    ],
],

Code Generation Settings

'generation' => [
    'architecture' => 'provider', // provider, bloc, riverpod
    'null_safety' => true,
    'use_freezed' => false,
    'use_json_annotation' => true,
    'generate_tests' => true,
    'generate_documentation' => true,
],

Model Analysis

'model_analysis' => [
    'include_relationships' => true,
    'include_accessors' => true,
    'include_timestamps' => true,
    'excluded_attributes' => [
        'password',
        'remember_token',
        'email_verified_at',
    ],
],

Generated Code Structure

flutter_output/
โ”œโ”€โ”€ models/
โ”‚   โ”œโ”€โ”€ user.dart
โ”‚   โ”œโ”€โ”€ user.g.dart (if using json_annotation)
โ”‚   โ””โ”€โ”€ post.dart
โ”œโ”€โ”€ services/
โ”‚   โ”œโ”€โ”€ api_service.dart (base HTTP client)
โ”‚   โ”œโ”€โ”€ user_service.dart
โ”‚   โ””โ”€โ”€ post_service.dart
โ”œโ”€โ”€ widgets/
โ”‚   โ”œโ”€โ”€ user_form.dart
โ”‚   โ”œโ”€โ”€ user_list.dart
โ”‚   โ”œโ”€โ”€ user_card.dart
โ”‚   โ””โ”€โ”€ post_form.dart
โ””โ”€โ”€ screens/
    โ”œโ”€โ”€ user_list_screen.dart
    โ”œโ”€โ”€ user_detail_screen.dart
    โ”œโ”€โ”€ user_create_screen.dart
    โ””โ”€โ”€ user_edit_screen.dart

Example Generated Code

Dart Model

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  final int id;
  final String name;
  final String email;
  final DateTime? emailVerifiedAt;
  final bool isActive;

  const User({
    required this.id,
    required this.name,
    required this.email,
    this.emailVerifiedAt,
    required this.isActive,
  });

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);

  User copyWith({
    int? id,
    String? name,
    String? email,
    DateTime? emailVerifiedAt,
    bool? isActive,
  }) {
    return User(
      id: id ?? this.id,
      name: name ?? this.name,
      email: email ?? this.email,
      emailVerifiedAt: emailVerifiedAt ?? this.emailVerifiedAt,
      isActive: isActive ?? this.isActive,
    );
  }
}

API Service

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/user.dart';
import 'api_service.dart';

class UserService {
  final ApiService _apiService;
  final String _endpoint;

  UserService(this._apiService, this._endpoint);

  Future<List<User>> getAll({int? page, Map<String, dynamic>? filters}) async {
    try {
      final queryParams = <String, String>{};
      if (page != null) queryParams['page'] = page.toString();

      final response = await _apiService.get(_endpoint, queryParams: queryParams);
      final List<dynamic> data = response['data'] ?? response;
      return data.map((json) => User.fromJson(json)).toList();
    } catch (e) {
      throw Exception('Failed to fetch User list: $e');
    }
  }

  Future<User> getById(int id) async {
    try {
      final response = await _apiService.get('$_endpoint/$id');
      final data = response['data'] ?? response;
      return User.fromJson(data);
    } catch (e) {
      throw Exception('Failed to fetch User with ID $id: $e');
    }
  }

  Future<User> create(Map<String, dynamic> data) async {
    try {
      final response = await _apiService.post(_endpoint, data);
      final responseData = response['data'] ?? response;
      return User.fromJson(responseData);
    } catch (e) {
      throw Exception('Failed to create User: $e');
    }
  }

  Future<User> update(int id, Map<String, dynamic> data) async {
    try {
      final response = await _apiService.put('$_endpoint/$id', data);
      final responseData = response['data'] ?? response;
      return User.fromJson(responseData);
    } catch (e) {
      throw Exception('Failed to update User with ID $id: $e');
    }
  }

  Future<bool> delete(int id) async {
    try {
      await _apiService.delete('$_endpoint/$id');
      return true;
    } catch (e) {
      throw Exception('Failed to delete User with ID $id: $e');
    }
  }
}

Integration with Flutter Project

  1. Copy generated files to your Flutter project:
cp -r flutter_output/* your_flutter_project/lib/
  1. Add dependencies to your pubspec.yaml:
dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  json_annotation: ^4.8.1
  provider: ^6.1.1  # if using Provider architecture

dev_dependencies:
  build_runner: ^2.4.7
  json_serializable: ^6.7.1
  1. Run code generation (if using json_annotation):
flutter packages pub run build_runner build
  1. Initialize API service in your app:
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UserListScreen(),
    );
  }
}

Advanced Usage

Custom Templates

You can customize the generated code by modifying the published templates in resources/views/flutter-generator/.

Excluding Models

Add models to exclude in your configuration:

'excluded_models' => [
    'App\\Models\\InternalModel',
    'Spatie\\Permission\\Models\\Role',
],

Route Integration

Use the --with-routes flag to analyze your API routes and generate additional service methods:

php artisan flutter:generate-service User --with-routes

This will analyze routes like:

  • GET /api/users/{user}/posts โ†’ getUserPosts(int userId)
  • POST /api/users/{user}/activate โ†’ activateUser(int userId)

Testing

Run the package tests:

composer test

Run with coverage:

composer test-coverage

Requirements

  • PHP 8.1+ (8.2, 8.3, 8.4 supported)
  • Laravel 10.0+, 11.0+, or 12.0+
  • Flutter 3.0+
  • Doctrine DBAL 3.0+ or 4.0+ (for database schema analysis)

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

Author

BasharShaeb - GitHub Profile

Changelog

See CHANGELOG.md for a list of changes.

License

This package is open-sourced software licensed under the MIT license.