ucprojects-backend / src /services /flutter_generator.py
AdeshRathod
feat: Initialize Flutter base project with essential files and configurations
01ae70d
Raw History Blame Contribute Delete
11.1 kB
import os
import shutil
import tempfile
import zipfile
from typing import List, Optional
from pydantic import BaseModel
import subprocess
class ProjectConfig(BaseModel):
app_name: str
package_name: str
primary_color: str # Hex
secondary_color: str # Hex
splash_screen: bool
onboarding_count: int # 0 means none
splash_screen: bool
onboarding_count: int # 0 means none
features: List[str] # ["auth", "bottom_nav", "profile"]
platforms: List[str] = ["android", "ios"] # Default to mobile
class FlutterGenerator:
def __init__(self):
pass
def generate(self, config: ProjectConfig) -> str:
"""
Generates a Flutter project zip using 'flutter create'.
Returns the path to the zip file.
"""
# 1. Create Temp Directory
temp_dir = tempfile.mkdtemp()
try:
# 2. Run flutter create
# split package name into org and name if possible, or just use as is
# flutter create --org com.example --project-name name .
# Extract org from package name (e.g. com.example.app -> com.example)
parts = config.package_name.split('.')
if len(parts) >= 2:
org = ".".join(parts[:-1])
else:
org = "com.example"
# Sanitize app_name for flutter project name (must be snake_case)
safe_app_name = config.app_name.lower().replace(" ", "_").replace("-", "_")
# Basic validation to ensure it starts with a letter could be added, but handled by flutter create output mostly
cmd = [
"flutter", "create",
"--org", org,
"--project-name", safe_app_name,
]
# Add platforms if specified
if config.platforms:
cmd.extend(["--platforms", ",".join(config.platforms)])
cmd.append(os.path.join(temp_dir, safe_app_name))
subprocess.run(cmd, check=True, shell=True) # shell=True for windows path resolution
project_root = os.path.join(temp_dir, safe_app_name)
# 3. Inject Dependencies (Safe Insert)
self._update_pubspec(project_root, config)
# 4. Generate Code Structure
self._generate_code_structure(project_root, config)
# 5. Inject Permissions
self._inject_permissions(project_root, config)
# 6. Zip Result
zip_path = shutil.make_archive(os.path.join(temp_dir, safe_app_name), 'zip', project_root)
return zip_path
except subprocess.CalledProcessError as e:
shutil.rmtree(temp_dir)
raise Exception(f"Flutter create failed: {e}")
except Exception as e:
shutil.rmtree(temp_dir)
raise e
def _rename_package(self, root: str, old_pkg: str, new_pkg: str):
# No longer needed as flutter create handles this
pass
def _update_app_name(self, root: str, name: str):
# No longer needed
pass
def _update_pubspec(self, root: str, config: ProjectConfig):
# Use flutter pub add to ensure compatibility with the local flutter version
dependencies = ["get", "google_fonts", "permission_handler"]
if "auth" in config.features:
dependencies.append("shared_preferences")
cmd = ["flutter", "pub", "add"] + dependencies
try:
# We run this inside the project root
subprocess.run(cmd, cwd=root, check=True, shell=True)
except subprocess.CalledProcessError as e:
# Fallback or log? For now let it raise so we know it failed
raise Exception(f"Failed to add dependencies: {e}")
def _generate_code_structure(self, root: str, config: ProjectConfig):
lib_path = os.path.join(root, 'lib')
# Create Directories
os.makedirs(os.path.join(lib_path, 'core', 'theme'), exist_ok=True)
os.makedirs(os.path.join(lib_path, 'core', 'services'), exist_ok=True)
os.makedirs(os.path.join(lib_path, 'getx', 'routes'), exist_ok=True)
os.makedirs(os.path.join(lib_path, 'modules'), exist_ok=True)
# Generator Helpers (In a real app these would be separate files/templates)
self._write_file(os.path.join(lib_path, 'main.dart'), self._get_main_dart(config))
self._write_file(os.path.join(lib_path, 'core', 'theme', 'app_theme.dart'), self._get_app_theme(config))
self._write_file(os.path.join(lib_path, 'getx', 'routes', 'app_pages.dart'), self._get_app_pages(config))
self._write_file(os.path.join(lib_path, 'getx', 'routes', 'app_routes.dart'), self._get_app_routes(config))
if "auth" in config.features:
self._generate_auth_module(lib_path)
if config.onboarding_count > 0:
self._generate_onboarding_module(lib_path, config.onboarding_count)
def _inject_permissions(self, root: str, config: ProjectConfig):
# Android
manifest_path = os.path.join(root, 'android/app/src/main/AndroidManifest.xml')
if os.path.exists(manifest_path):
with open(manifest_path, 'r') as f:
content = f.read()
perms = ""
if "profile" in config.features:
perms += ' <uses-permission android:name="android.permission.CAMERA"/>\n'
perms += ' <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>\n'
content = content.replace('<!-- Permissions Placeholder -->', perms)
with open(manifest_path, 'w') as f:
f.write(content)
def _write_file(self, path, content):
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
# --- Content Generators ---
def _get_main_dart(self, config: ProjectConfig):
return f"""
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'core/theme/app_theme.dart';
import 'getx/routes/app_pages.dart';
void main() {{
runApp(const MyApp());
}}
class MyApp extends StatelessWidget {{
const MyApp({{super.key}});
@override
Widget build(BuildContext context) {{
return GetMaterialApp(
title: '{config.app_name}',
theme: AppTheme.lightTheme,
initialRoute: AppPages.INITIAL,
getPages: AppPages.routes,
);
}}
}}
"""
def _get_app_theme(self, config: ProjectConfig):
return f"""
import 'package:flutter/material.dart';
class AppTheme {{
static final lightTheme = ThemeData(
primaryColor: Color(int.parse("0xFF{config.primary_color.replace('#', '')}")),
colorScheme: ColorScheme.fromSwatch().copyWith(
primary: Color(int.parse("0xFF{config.primary_color.replace('#', '')}")),
secondary: Color(int.parse("0xFF{config.secondary_color.replace('#', '')}")),
),
useMaterial3: true,
);
}}
"""
def _get_app_pages(self, config: ProjectConfig):
initial = "Routes.HOME"
imports = []
pages = []
# Always add specific feature imports and pages
if config.onboarding_count > 0:
initial = "Routes.ONBOARDING"
imports.append("import '../../modules/onboarding/onboarding_view.dart';")
pages.append(" GetPage(name: Routes.ONBOARDING, page: () => OnboardingView()),")
elif "auth" in config.features:
initial = "Routes.LOGIN"
imports.append("import '../../modules/auth/login_view.dart';")
imports.append("import '../../modules/auth/auth_controller.dart';")
pages.append(" GetPage(name: Routes.LOGIN, page: () => LoginView(), binding: BindingsBuilder(() { Get.put(AuthController()); })),")
# Join imports
imports_str = "\n".join(imports)
pages_str = "\n".join(pages)
return f"""
import 'package:get/get.dart';
import 'app_routes.dart';
{imports_str}
class AppPages {{
static const INITIAL = {initial};
static final List<GetPage> routes = [
{pages_str}
];
}}
"""
def _get_app_routes(self, config: ProjectConfig):
return """
abstract class Routes {
static const HOME = '/home';
static const LOGIN = '/login';
static const REGISTER = '/register';
static const ONBOARDING = '/onboarding';
}
"""
def _generate_auth_module(self, lib_path):
auth_path = os.path.join(lib_path, 'modules', 'auth')
os.makedirs(auth_path, exist_ok=True)
# Controller
self._write_file(os.path.join(auth_path, 'auth_controller.dart'), """
import 'package:get/get.dart';
class AuthController extends GetxController {
var isLoading = false.obs;
void login(String username, String password) {
isLoading.value = true;
Future.delayed(Duration(seconds: 2), () {
isLoading.value = false;
Get.snackbar("Success", "Logged in as $username");
});
}
}
""")
# View
self._write_file(os.path.join(auth_path, 'login_view.dart'), """
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'auth_controller.dart';
class LoginView extends GetView<AuthController> {
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Login")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(controller: usernameController, decoration: InputDecoration(labelText: "Username")),
TextField(controller: passwordController, decoration: InputDecoration(labelText: "Password"), obscureText: true,),
SizedBox(height: 20),
Obx(() => controller.isLoading.value
? CircularProgressIndicator()
: ElevatedButton(
onPressed: () => controller.login(usernameController.text, passwordController.text),
child: Text("Login")
)
)
],
),
),
);
}
}
""")
def _generate_onboarding_module(self, lib_path, count):
onboarding_path = os.path.join(lib_path, 'modules', 'onboarding')
os.makedirs(onboarding_path, exist_ok=True)
# View
slide_widgets = ""
for i in range(1, count + 1):
slide_widgets += f"Center(child: Text('Onboarding Screen {i}')),\n"
self._write_file(os.path.join(onboarding_path, 'onboarding_view.dart'), f"""
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class OnboardingView extends StatelessWidget {{
@override
Widget build(BuildContext context) {{
return Scaffold(
body: PageView(
children: [
{slide_widgets}
],
),
);
}}
}}
""")