Spaces:
Sleeping
Sleeping
Download agents/flutter_screen_generator.py from OneWeekApp/space-ac-design: direct link, hf CLI and curl.
- Browser
- Download file 220 kB
-
https://huggingface.co/spaces/OneWeekApp/space-ac-design/resolve/main/agents/flutter_screen_generator.py
- Command line
-
hf download hf://spaces/OneWeekApp/space-ac-design/agents/flutter_screen_generator.py
-
curl -L -o flutter_screen_generator.py https://huggingface.co/spaces/OneWeekApp/space-ac-design/resolve/main/agents/flutter_screen_generator.py
220 kB
"""
AC3: Flutter Screen Generator Agent
Generates Flutter/Dart screen code using AI Planning (DeepSeek Coder) + Jinja2 templates.
Takes design themes from AC2 and generates runnable Dart code for DartPad.
"""
import os
import json
import requests
from typing import Dict, Any, List
from jinja2 import Environment, FileSystemLoader, select_autoescape
class FlutterScreenGenerator:
"""
Agent that generates Flutter screen code using AI planning and templates
"""
# BACKGROUND CATALOG - 30 unique variations
BACKGROUND_CATALOG = {
# GRADIENTS (6)
"gradient_linear": {"category": "gradients", "name": "Linear Gradient", "complexity": "simple"},
"gradient_radial": {"category": "gradients", "name": "Radial Gradient", "complexity": "simple"},
"gradient_angular": {"category": "gradients", "name": "Angular Gradient", "complexity": "medium"},
"gradient_sweep": {"category": "gradients", "name": "Sweep Gradient", "complexity": "medium"},
"gradient_mesh": {"category": "gradients", "name": "Mesh Gradient", "complexity": "complex"},
"gradient_diagonal": {"category": "gradients", "name": "Diagonal Gradient", "complexity": "simple"},
# WAVES (5)
"waves_smooth": {"category": "waves", "name": "Smooth Waves", "complexity": "medium"},
"waves_sharp": {"category": "waves", "name": "Sharp Waves", "complexity": "medium"},
"waves_layered": {"category": "waves", "name": "Layered Waves", "complexity": "complex"},
"waves_curved": {"category": "waves", "name": "Curved Waves", "complexity": "medium"},
"waves_minimal": {"category": "waves", "name": "Minimal Wave", "complexity": "simple"},
# GEOMETRIC (6)
"geometric_circles": {"category": "geometric", "name": "Floating Circles", "complexity": "medium"},
"geometric_triangles": {"category": "geometric", "name": "Triangle Pattern", "complexity": "medium"},
"geometric_hexagons": {"category": "geometric", "name": "Hexagon Grid", "complexity": "complex"},
"geometric_grid": {"category": "geometric", "name": "Dot Grid", "complexity": "simple"},
"geometric_stripes": {"category": "geometric", "name": "Diagonal Stripes", "complexity": "simple"},
"geometric_diamonds": {"category": "geometric", "name": "Diamond Shapes", "complexity": "medium"},
# ORGANIC (4)
"organic_blobs": {"category": "organic", "name": "Blob Shapes", "complexity": "complex"},
"organic_fluid": {"category": "organic", "name": "Fluid Effect", "complexity": "complex"},
"organic_noise": {"category": "organic", "name": "Noise Texture", "complexity": "medium"},
"organic_clouds": {"category": "organic", "name": "Cloud Shapes", "complexity": "medium"},
# PATTERNS (4)
"pattern_dots": {"category": "patterns", "name": "Dot Pattern", "complexity": "simple"},
"pattern_lines": {"category": "patterns", "name": "Line Pattern", "complexity": "simple"},
"pattern_chevron": {"category": "patterns", "name": "Chevron Pattern", "complexity": "medium"},
"pattern_zigzag": {"category": "patterns", "name": "Zigzag Pattern", "complexity": "medium"},
# ABSTRACT (5)
"abstract_crystalline": {"category": "abstract", "name": "Crystalline", "complexity": "complex"},
"abstract_voronoi": {"category": "abstract", "name": "Voronoi Diagram", "complexity": "complex"},
"abstract_particles": {"category": "abstract", "name": "Particle Field", "complexity": "medium"},
"abstract_rays": {"category": "abstract", "name": "Light Rays", "complexity": "medium"},
"abstract_constellation": {"category": "abstract", "name": "Star Constellation", "complexity": "medium"},
}
HEADER_CATALOG = {
# SOCIAL & PROFILE (5)
"profile_avatar_menu": {"name": "Profile Avatar Menu", "complexity": "medium", "description": "Avatar, username, location, menu"},
"avatar_notification_cart": {"name": "Avatar + Notifications + Cart", "complexity": "medium", "description": "User avatar, notification bell, shopping cart"},
"profile_stats_share": {"name": "Profile Stats Share", "complexity": "complex", "description": "Avatar, followers/following stats, share button"},
"social_search_filter": {"name": "Social Search Filter", "complexity": "medium", "description": "Search bar, filter icon, settings"},
"messenger_header": {"name": "Messenger Header", "complexity": "medium", "description": "Back button, user avatar, call/video icons"},
# LOCATION & DELIVERY (4)
"location_picker": {"name": "Location Picker", "complexity": "medium", "description": "GPS icon, current location, dropdown"},
"delivery_address_time": {"name": "Delivery Address + Time", "complexity": "complex", "description": "Address, delivery time estimate, change button"},
"map_search_location": {"name": "Map Search Location", "complexity": "medium", "description": "Search bar with GPS, current location"},
"ride_pickup_header": {"name": "Ride Pickup Header", "complexity": "complex", "description": "From/To locations, swap button"},
# E-COMMERCE (3)
"shop_cart_wishlist": {"name": "Shop Cart Wishlist", "complexity": "medium", "description": "Logo, search, wishlist, cart with badge"},
"category_filter_sort": {"name": "Category Filter Sort", "complexity": "medium", "description": "Category dropdown, filter, sort buttons"},
"product_search_scan": {"name": "Product Search Scan", "complexity": "medium", "description": "Search bar, barcode scan, voice search"},
# FINANCE & WALLET (3)
"wallet_balance_qr": {"name": "Wallet Balance QR", "complexity": "complex", "description": "Avatar, balance display, QR code button"},
"banking_accounts_menu": {"name": "Banking Accounts Menu", "complexity": "medium", "description": "Account selector, balance, menu"},
"crypto_portfolio_refresh": {"name": "Crypto Portfolio Refresh", "complexity": "medium", "description": "Total value, 24h change, refresh button"},
# HEALTH & FITNESS (2)
"fitness_streak_profile": {"name": "Fitness Streak Profile", "complexity": "complex", "description": "Avatar, streak counter, achievements"},
"workout_timer_pause": {"name": "Workout Timer Pause", "complexity": "medium", "description": "Timer display, pause/play, skip buttons"},
# MEDIA & ENTERTAINMENT (3)
"video_player_controls": {"name": "Video Player Controls", "complexity": "medium", "description": "Back, title, cast, more options"},
"music_player_header": {"name": "Music Player Header", "complexity": "simple", "description": "Back button, song title, artist, favorite"},
"news_category_tabs": {"name": "News Category Tabs", "complexity": "medium", "description": "Logo, category tabs, bookmark icon"},
}
FOOTER_CATALOG = {
# CLASSIC TAB BARS (6)
"classic_4_icons": {"name": "Classic 4 Icons", "complexity": "simple", "description": "Standard 4-icon bottom bar"},
"classic_5_icons": {"name": "Classic 5 Icons", "complexity": "simple", "description": "Standard 5-icon bottom bar with labels"},
"compact_icons_badge": {"name": "Compact Icons + Badge", "complexity": "medium", "description": "Small icons with notification badges"},
"labeled_vertical": {"name": "Labeled Vertical", "complexity": "simple", "description": "Large icons with labels below"},
"colored_active": {"name": "Colored Active", "complexity": "medium", "description": "Active item with color fill background"},
"icon_label_inline": {"name": "Icon Label Inline", "complexity": "medium", "description": "Icons and labels side by side"},
# FLOATING & FAB STYLES (5)
"floating_rounded": {"name": "Floating Rounded", "complexity": "medium", "description": "Rounded floating bar with shadow"},
"floating_fab_center": {"name": "Floating FAB Center", "complexity": "complex", "description": "Floating bar with centered FAB button"},
"floating_translucent": {"name": "Floating Translucent", "complexity": "medium", "description": "Semi-transparent floating bar"},
"floating_pills_bar": {"name": "Floating Pills Bar", "complexity": "medium", "description": "Pill-shaped buttons in floating bar"},
"dual_fab": {"name": "Dual FAB", "complexity": "complex", "description": "Two floating action buttons"},
# CURVED & SHAPED DESIGNS (5)
"curved_top": {"name": "Curved Top", "complexity": "medium", "description": "Bar with curved top edge"},
"notched_center": {"name": "Notched Center", "complexity": "complex", "description": "Center notch for FAB button"},
"wave_top": {"name": "Wave Top", "complexity": "complex", "description": "Wave-shaped top border"},
"island_bar": {"name": "Island Bar", "complexity": "medium", "description": "Detached island-style navigation"},
"arc_active": {"name": "Arc Active", "complexity": "complex", "description": "Arc indicator for active item"},
# SEGMENTED & PILLS (5)
"segmented_control": {"name": "Segmented Control", "complexity": "medium", "description": "iOS-style segmented control"},
"pill_buttons": {"name": "Pill Buttons", "complexity": "medium", "description": "Individual pill-shaped buttons"},
"grouped_pills": {"name": "Grouped Pills", "complexity": "medium", "description": "Pills grouped in container"},
"slider_nav": {"name": "Slider Nav", "complexity": "complex", "description": "Sliding indicator under items"},
"morphing_pills": {"name": "Morphing Pills", "complexity": "complex", "description": "Pills that morph on selection"},
# MINIMALIST & GESTURE (4)
"minimal_dots": {"name": "Minimal Dots", "complexity": "simple", "description": "Simple dots navigation"},
"gesture_swipe": {"name": "Gesture Swipe", "complexity": "simple", "description": "Swipe gesture bar"},
"thin_bar": {"name": "Thin Bar", "complexity": "simple", "description": "Ultra-thin navigation strip"},
"invisible_tap": {"name": "Invisible Tap", "complexity": "simple", "description": "Invisible tap zones with subtle indicators"},
# ADVANCED & INTERACTIVE (5)
"expandable_drawer": {"name": "Expandable Drawer", "complexity": "complex", "description": "Bottom drawer that expands up"},
"grid_menu": {"name": "Grid Menu", "complexity": "complex", "description": "Grid layout of menu items"},
"carousel_nav": {"name": "Carousel Nav", "complexity": "complex", "description": "Scrollable carousel navigation"},
"context_aware": {"name": "Context Aware", "complexity": "complex", "description": "Changes based on scroll/context"},
"nested_menu": {"name": "Nested Menu", "complexity": "complex", "description": "Two-level nested navigation"},
}
CARD_CATALOG = {
# PRODUCT & SHOPPING (6)
"product_vertical": {"name": "Product Vertical", "complexity": "simple", "description": "Image on top, title, price below"},
"product_horizontal": {"name": "Product Horizontal", "complexity": "simple", "description": "Image left, info right, horizontal layout"},
"product_badge": {"name": "Product with Badge", "complexity": "medium", "description": "Product card with sale/new badge"},
"product_rating": {"name": "Product with Rating", "complexity": "medium", "description": "Product with star rating and reviews"},
"product_grid_compact": {"name": "Product Grid Compact", "complexity": "simple", "description": "Compact grid item, minimal info"},
"product_featured": {"name": "Product Featured", "complexity": "complex", "description": "Large featured product with gradient overlay"},
# PROFILE & SOCIAL (5)
"profile_user_card": {"name": "Profile User Card", "complexity": "medium", "description": "Avatar, name, bio, follow button"},
"profile_stats_card": {"name": "Profile Stats Card", "complexity": "complex", "description": "Avatar, name, stats (followers/posts/likes)"},
"social_post_card": {"name": "Social Post Card", "complexity": "complex", "description": "Avatar, name, post text, image, likes/comments"},
"social_story_card": {"name": "Social Story Card", "complexity": "simple", "description": "Circular avatar with gradient ring"},
"contact_card": {"name": "Contact Card", "complexity": "medium", "description": "Avatar, name, email/phone, action buttons"},
# CONTENT & MEDIA (5)
"article_card": {"name": "Article Card", "complexity": "medium", "description": "Image, title, excerpt, read time"},
"video_card": {"name": "Video Card", "complexity": "medium", "description": "Thumbnail, play button, duration, title"},
"podcast_card": {"name": "Podcast Card", "complexity": "medium", "description": "Cover art, episode title, duration, play button"},
"news_headline": {"name": "News Headline", "complexity": "simple", "description": "Small thumbnail, headline, timestamp"},
"blog_featured": {"name": "Blog Featured", "complexity": "complex", "description": "Large image, overlay text, category tag"},
# STATS & ANALYTICS (4)
"stats_metric": {"name": "Stats Metric", "complexity": "simple", "description": "Icon, metric value, label, trend"},
"stats_comparison": {"name": "Stats Comparison", "complexity": "medium", "description": "Two metrics side by side with arrows"},
"stats_progress": {"name": "Stats Progress", "complexity": "medium", "description": "Label, progress bar, percentage"},
"stats_chart": {"name": "Stats Chart", "complexity": "complex", "description": "Mini chart visualization with data"},
# MESSAGING & NOTIFICATIONS (4)
"message_preview": {"name": "Message Preview", "complexity": "medium", "description": "Avatar, sender, preview text, timestamp"},
"notification_card": {"name": "Notification Card", "complexity": "medium", "description": "Icon, title, message, timestamp, badge"},
"alert_card": {"name": "Alert Card", "complexity": "simple", "description": "Icon, alert message, dismiss button"},
"chat_bubble": {"name": "Chat Bubble", "complexity": "simple", "description": "Message bubble with tail, timestamp"},
# SPECIAL CARDS (6)
"pricing_plan": {"name": "Pricing Plan", "complexity": "complex", "description": "Plan name, price, features list, CTA button"},
"review_card": {"name": "Review Card", "complexity": "medium", "description": "Avatar, name, stars, review text, date"},
"event_card": {"name": "Event Card", "complexity": "medium", "description": "Date badge, event title, location, attendees"},
"offer_coupon": {"name": "Offer Coupon", "complexity": "medium", "description": "Dashed border, discount, code, expiry"},
"weather_card": {"name": "Weather Card", "complexity": "complex", "description": "Icon, temperature, location, forecast"},
"ticket_card": {"name": "Ticket Card", "complexity": "complex", "description": "Barcode, event info, seat number, tear line"},
# E-COMMERCE EXTENDED (15)
"cart_item": {"name": "Cart Item", "complexity": "medium", "description": "Product image, name, quantity selector, price"},
"wishlist_item": {"name": "Wishlist Item", "complexity": "simple", "description": "Product with heart icon, remove button"},
"checkout_step": {"name": "Checkout Step", "complexity": "medium", "description": "Step indicator, form fields, progress"},
"shipping_option": {"name": "Shipping Option", "complexity": "simple", "description": "Radio button, carrier name, price, ETA"},
"product_review": {"name": "Product Review", "complexity": "medium", "description": "Stars, verified badge, review text, helpful count"},
"category_grid": {"name": "Category Grid", "complexity": "simple", "description": "Icon, category name, item count"},
"filter_chip": {"name": "Filter Chip", "complexity": "simple", "description": "Selected state, label, close icon"},
"order_summary": {"name": "Order Summary", "complexity": "complex", "description": "Items list, subtotal, shipping, total"},
"payment_method": {"name": "Payment Method", "complexity": "medium", "description": "Card icon, last 4 digits, expiry, default badge"},
"order_tracking": {"name": "Order Tracking", "complexity": "complex", "description": "Timeline, status updates, estimated delivery"},
"brand_showcase": {"name": "Brand Showcase", "complexity": "medium", "description": "Logo, brand name, follow button, product count"},
"size_selector": {"name": "Size Selector", "complexity": "simple", "description": "Size options, selected state, stock indicator"},
"color_picker": {"name": "Color Picker", "complexity": "simple", "description": "Color swatches, selected state, color name"},
"flash_sale": {"name": "Flash Sale", "complexity": "complex", "description": "Countdown timer, discount, product image, urgency"},
"related_products": {"name": "Related Products", "complexity": "medium", "description": "Small product cards, horizontal scroll"},
# SOCIAL EXTENDED (10)
"comment_thread": {"name": "Comment Thread", "complexity": "medium", "description": "Avatar, username, comment, reply count, likes"},
"reaction_bar": {"name": "Reaction Bar", "complexity": "simple", "description": "Like, love, haha, wow emoji reactions"},
"share_sheet": {"name": "Share Sheet", "complexity": "medium", "description": "Share options, apps icons, copy link"},
"follower_item": {"name": "Follower Item", "complexity": "medium", "description": "Avatar, username, mutual friends, follow button"},
"story_ring": {"name": "Story Ring", "complexity": "simple", "description": "Circular avatar with gradient ring, unseen indicator"},
"reel_preview": {"name": "Reel Preview", "complexity": "complex", "description": "Video thumbnail, play icon, views, duration"},
"live_streaming": {"name": "Live Streaming", "complexity": "complex", "description": "Live badge, viewer count, thumbnail, host"},
"poll_card": {"name": "Poll Card", "complexity": "medium", "description": "Question, options with percentages, vote count"},
"mention_tag": {"name": "Mention Tag", "complexity": "simple", "description": "Username with @ symbol, tappable"},
"group_member": {"name": "Group Member", "complexity": "medium", "description": "Avatar, name, role badge, admin controls"},
# FINANCE & BANKING (10)
"account_balance": {"name": "Account Balance", "complexity": "medium", "description": "Account type, balance, account number, view details"},
"transaction_item": {"name": "Transaction Item", "complexity": "medium", "description": "Merchant, amount, date, category icon, pending"},
"credit_card": {"name": "Credit Card", "complexity": "complex", "description": "Card design, number, expiry, chip, network logo"},
"transfer_form": {"name": "Transfer Form", "complexity": "complex", "description": "Recipient, amount, note, schedule, confirm"},
"investment_item": {"name": "Investment Item", "complexity": "medium", "description": "Stock symbol, current price, change %, chart mini"},
"crypto_wallet": {"name": "Crypto Wallet", "complexity": "medium", "description": "Coin icon, symbol, balance, USD value, change %"},
"bill_payment": {"name": "Bill Payment", "complexity": "medium", "description": "Biller logo, amount due, due date, pay button"},
"budget_category": {"name": "Budget Category", "complexity": "medium", "description": "Category icon, spent/budget, progress bar"},
"loan_summary": {"name": "Loan Summary", "complexity": "complex", "description": "Loan type, outstanding, EMI, next payment"},
"statement_month": {"name": "Statement Month", "complexity": "simple", "description": "Month/year, total spent, download PDF"},
# HEALTH & FITNESS (10)
"workout_exercise": {"name": "Workout Exercise", "complexity": "medium", "description": "Exercise name, sets, reps, rest timer"},
"nutrition_log": {"name": "Nutrition Log", "complexity": "medium", "description": "Food name, calories, macros, portion size"},
"step_counter": {"name": "Step Counter", "complexity": "simple", "description": "Step count, goal, circular progress"},
"heart_rate": {"name": "Heart Rate", "complexity": "medium", "description": "BPM value, status, mini graph, timestamp"},
"sleep_tracker": {"name": "Sleep Tracker", "complexity": "complex", "description": "Sleep duration, quality score, phases chart"},
"water_intake": {"name": "Water Intake", "complexity": "simple", "description": "Glasses filled, goal, add button"},
"bmi_calculator": {"name": "BMI Calculator", "complexity": "medium", "description": "BMI value, category, height/weight inputs"},
"calorie_goal": {"name": "Calorie Goal", "complexity": "medium", "description": "Consumed, burned, remaining, circular progress"},
"meditation_session": {"name": "Meditation Session", "complexity": "medium", "description": "Duration, type, play button, background"},
"weight_progress": {"name": "Weight Progress", "complexity": "complex", "description": "Current, goal, change, timeline graph"},
# EDUCATION & LEARNING (8)
"course_card": {"name": "Course Card", "complexity": "complex", "description": "Thumbnail, title, instructor, rating, price, students"},
"lesson_item": {"name": "Lesson Item", "complexity": "medium", "description": "Number, title, duration, completed checkmark"},
"quiz_question": {"name": "Quiz Question", "complexity": "complex", "description": "Question, multiple choice options, submit"},
"certificate_card": {"name": "Certificate Card", "complexity": "complex", "description": "Certificate design, course name, date, download"},
"learning_progress": {"name": "Learning Progress", "complexity": "medium", "description": "Course, percentage, modules completed"},
"assignment_card": {"name": "Assignment Card", "complexity": "medium", "description": "Title, due date, status, upload button"},
"grade_item": {"name": "Grade Item", "complexity": "simple", "description": "Subject, grade, points, feedback link"},
"study_streak": {"name": "Study Streak", "complexity": "simple", "description": "Days count, flame icon, calendar"},
# TRAVEL & TOURISM (8)
"flight_card": {"name": "Flight Card", "complexity": "complex", "description": "Airline, departure/arrival, duration, price, stops"},
"hotel_listing": {"name": "Hotel Listing", "complexity": "complex", "description": "Photo, name, stars, amenities, price per night"},
"booking_confirm": {"name": "Booking Confirmation", "complexity": "complex", "description": "Booking ID, dates, guest info, QR code"},
"destination_card": {"name": "Destination Card", "complexity": "medium", "description": "City image, name, country, popular, deals"},
"itinerary_day": {"name": "Itinerary Day", "complexity": "complex", "description": "Day number, activities timeline, locations"},
"map_location": {"name": "Map Location", "complexity": "medium", "description": "Place name, address, distance, directions button"},
"travel_review": {"name": "Travel Review", "complexity": "medium", "description": "User, stars, photos, helpful count, date"},
"passport_info": {"name": "Passport Info", "complexity": "medium", "description": "Passport number, expiry, nationality, upload"},
# FOOD & RESTAURANT (8)
"menu_item": {"name": "Menu Item", "complexity": "medium", "description": "Dish photo, name, description, price, add button"},
"recipe_card": {"name": "Recipe Card", "complexity": "complex", "description": "Photo, title, cook time, difficulty, servings"},
"order_item": {"name": "Order Item", "complexity": "medium", "description": "Item name, quantity, customizations, price"},
"reservation_slot": {"name": "Reservation Slot", "complexity": "simple", "description": "Time, available seats, book button"},
"delivery_tracker": {"name": "Delivery Tracker", "complexity": "complex", "description": "Order status, driver location, ETA"},
"restaurant_rating": {"name": "Restaurant Rating", "complexity": "medium", "description": "Stars, food/service/ambience scores"},
"ingredient_list": {"name": "Ingredient List", "complexity": "simple", "description": "Ingredient, quantity, checkbox"},
"dietary_tag": {"name": "Dietary Tag", "complexity": "simple", "description": "Vegan/gluten-free badge, icon, color"},
# REAL ESTATE (7)
"property_listing": {"name": "Property Listing", "complexity": "complex", "description": "Photos, price, beds/baths, sqft, location"},
"agent_card": {"name": "Agent Card", "complexity": "medium", "description": "Photo, name, properties sold, rating, contact"},
"virtual_tour": {"name": "Virtual Tour", "complexity": "medium", "description": "360 view icon, room name, view button"},
"mortgage_calc": {"name": "Mortgage Calculator", "complexity": "complex", "description": "Loan amount, interest, term, monthly payment"},
"property_compare": {"name": "Property Compare", "complexity": "complex", "description": "Side by side specs, price, features"},
"favorite_property": {"name": "Favorite Property", "complexity": "medium", "description": "Small photo, address, price, remove heart"},
"open_house": {"name": "Open House", "complexity": "medium", "description": "Date, time, address, RSVP button"},
# MUSIC & AUDIO (7)
"playlist_card": {"name": "Playlist Card", "complexity": "medium", "description": "Cover art, name, creator, song count, play"},
"song_item": {"name": "Song Item", "complexity": "medium", "description": "Album art, title, artist, duration, more menu"},
"album_cover": {"name": "Album Cover", "complexity": "simple", "description": "Large artwork, album name, artist, year"},
"artist_profile": {"name": "Artist Profile", "complexity": "complex", "description": "Photo, name, followers, top songs, bio"},
"podcast_episode": {"name": "Podcast Episode", "complexity": "medium", "description": "Episode art, title, duration, date, play"},
"radio_station": {"name": "Radio Station", "complexity": "simple", "description": "Logo, name, genre, now playing, tune"},
"equalizer_preset": {"name": "Equalizer Preset", "complexity": "medium", "description": "Preset name, frequency bars, apply button"},
# GAMING (6)
"achievement_badge": {"name": "Achievement Badge", "complexity": "medium", "description": "Badge icon, name, points, unlock date"},
"leaderboard_entry": {"name": "Leaderboard Entry", "complexity": "medium", "description": "Rank, avatar, username, score, change"},
"character_card": {"name": "Character Card", "complexity": "complex", "description": "Character art, name, level, stats, abilities"},
"game_item": {"name": "Game Item", "complexity": "simple", "description": "Item icon, name, rarity, quantity"},
"quest_card": {"name": "Quest Card", "complexity": "medium", "description": "Title, objective, progress, rewards"},
"player_stats": {"name": "Player Stats", "complexity": "complex", "description": "Level, XP bar, K/D ratio, win rate"},
# PRODUCTIVITY (6)
"task_item": {"name": "Task Item", "complexity": "simple", "description": "Checkbox, task name, due date, priority"},
"note_card": {"name": "Note Card", "complexity": "simple", "description": "Title, preview text, tags, timestamp"},
"reminder_alert": {"name": "Reminder Alert", "complexity": "medium", "description": "Icon, reminder text, time, snooze/done"},
"timer_widget": {"name": "Timer Widget", "complexity": "medium", "description": "Countdown, circular progress, start/pause"},
"calendar_event": {"name": "Calendar Event", "complexity": "medium", "description": "Time, title, location, attendees"},
"project_card": {"name": "Project Card", "complexity": "complex", "description": "Name, progress %, team members, deadline"},
# DASHBOARD WIDGETS (8)
"kpi_card": {"name": "KPI Card", "complexity": "medium", "description": "Label, value, trend arrow, percentage change"},
"pie_chart": {"name": "Pie Chart Widget", "complexity": "complex", "description": "Donut chart, segments, legend, percentages"},
"line_graph": {"name": "Line Graph Widget", "complexity": "complex", "description": "Time series data, multiple lines, axes"},
"bar_chart": {"name": "Bar Chart Widget", "complexity": "medium", "description": "Vertical bars, labels, values"},
"metric_alert": {"name": "Metric Alert", "complexity": "medium", "description": "Warning/error icon, metric, threshold, action"},
"summary_widget": {"name": "Summary Widget", "complexity": "complex", "description": "Multiple metrics, sparklines, period selector"},
"activity_feed": {"name": "Activity Feed Item", "complexity": "medium", "description": "Icon, action description, user, timestamp"},
"heatmap_widget": {"name": "Heatmap Widget", "complexity": "complex", "description": "Grid calendar, intensity colors, tooltip"},
}
def __init__(self):
self.name = "flutter_screen_generator"
self.description = "Generates Flutter/Dart screen code for DartPad"
# DeepSeek API (OpenAI-compatible)
self.deepseek_api_key = os.getenv("DEEPSEEK_API_KEY", "")
self.deepseek_base_url = "https://api.deepseek.com/v1/chat/completions"
self.model = "deepseek-coder" # DeepSeek Coder model for code generation
# Jinja2 setup with custom delimiters (to avoid conflict with Dart ${})
template_dir = os.path.join(os.path.dirname(__file__), '..', 'templates', 'dart')
self.jinja_env = Environment(
loader=FileSystemLoader(template_dir) if os.path.exists(template_dir) else FileSystemLoader('.'),
autoescape=select_autoescape(),
variable_start_string='<{',
variable_end_string='}>',
block_start_string='<{%',
block_end_string='%}>',
comment_start_string='<{#',
comment_end_string='#}>',
trim_blocks=True,
lstrip_blocks=True,
)
def _call_deepseek_api(self, messages: List[Dict[str, str]], max_tokens: int = 800, temperature: float = 0.7) -> str:
"""
Call DeepSeek API (OpenAI-compatible)
Args:
messages: List of message dicts with 'role' and 'content'
max_tokens: Maximum tokens to generate
temperature: Sampling temperature
Returns:
Generated text content
"""
if not self.deepseek_api_key:
raise ValueError("DEEPSEEK_API_KEY not configured")
print(f"📡 Calling DeepSeek API: model={self.model}, max_tokens={max_tokens}")
headers = {
"Authorization": f"Bearer {self.deepseek_api_key}",
"Content-Type": "application/json"
}
payload = {
"model": self.model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature
}
response = requests.post(
self.deepseek_base_url,
headers=headers,
json=payload,
timeout=30
)
response.raise_for_status()
result = response.json()
print(f"✅ DeepSeek API call successful, response length: {len(result['choices'][0]['message']['content'])} chars")
return result["choices"][0]["message"]["content"]
def process(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Generate Flutter screen code from design theme
Args:
input_data: {
"theme": {...}, # Complete theme from AC2
"app_type": "fitness|banking|rider|ecommerce|social",
"screens": ["home", "detail", "profile"]
}
Returns:
{
"screens": [
{
"name": "home",
"code": "...", # Complete Dart code
"lines": 450,
"components": ["StatsCard", "FeatureGrid"]
}
]
}
"""
try:
theme = input_data.get("theme", {})
app_type = input_data.get("app_type", "generic")
screen_types = input_data.get("screens", ["home"])
custom_prompt = input_data.get("custom_prompt", "") # Get custom prompt
# GENERA SOLO 1 SCHERMATA (sempre home)
screen_type = "home"
try:
# Step 1: AI generates 4 intelligent variants based on theme + app_type
print(f"🤖 AI generating 4 intelligent variants for {app_type}...")
if self.deepseek_api_key:
variants = self._generate_variants_with_ai(theme, app_type, custom_prompt)
else:
print("⚠️ No DEEPSEEK_API_KEY - using fallback variants")
variants = self._get_fallback_variants(app_type)
# Step 2: Generate Dart code for each variant
screens = []
for i, variant in enumerate(variants):
print(f" 🎨 Generating variant {i+1}: {variant['name']}")
dart_code = self._generate_complete_screen(
theme=theme,
app_type=app_type,
variant=variant
)
screens.append({
"name": variant["name"],
"description": variant.get("description", ""),
"code": dart_code,
"lines": len(dart_code.split('\n')),
"bg_style": variant["background"],
"header_type": variant["header"],
"footer_type": variant["footer"],
"cards": variant.get("cards", []),
"reasoning": variant.get("reasoning", ""),
"status": "generated"
})
print(f" ✅ Generated: {variant['name']}")
except Exception as e:
print(f"❌ Error generating screen: {e}")
import traceback
traceback.print_exc()
# Fallback
screens = [{
"name": screen_type,
"code": self._generate_simple_fallback(theme, screen_type),
"lines": 200,
"components": [],
"status": "error"
}]
return {
"screens": screens,
"theme_name": theme.get("name", "Unknown"),
"app_type": app_type,
"total_lines": sum(s.get("lines", 0) for s in screens)
}
except Exception as e:
print(f"❌ Critical error in process(): {e}")
import traceback
traceback.print_exc()
# Even on critical error, try to generate at least one fallback screen
try:
theme = input_data.get("theme", {})
app_type = input_data.get("app_type", "generic")
screens = input_data.get("screens", ["home"])
fallback_screens = [{
"name": screens[0] if screens else "home",
"code": self._generate_simple_fallback(theme, screens[0] if screens else "home"),
"lines": 200,
"components": [],
"status": "critical_error_fallback"
}]
return {
"screens": fallback_screens,
"error": str(e),
"theme_name": theme.get("name", "Error"),
"app_type": app_type,
"total_lines": 200
}
except:
# Last resort - return minimal structure
return {
"screens": [],
"error": f"Critical error: {str(e)}",
"theme_name": "Error",
"app_type": "unknown",
"total_lines": 0
}
def _generate_plan(self, theme: Dict[str, Any], app_type: str, screen_type: str) -> Dict[str, Any]:
"""
Use DeepSeek Coder to generate architectural plan for the screen
Returns JSON plan with sections, components, and layout decisions
"""
prompt = self._build_planning_prompt(theme, app_type, screen_type)
try:
# Call DeepSeek API
generated_text = self._call_deepseek_api(
messages=[{"role": "user", "content": prompt}],
max_tokens=1000,
temperature=0.7
)
# Extract JSON from response
return self._extract_json_from_text(generated_text)
except Exception as e:
print(f"AI Planning error: {e}")
return None
def _build_planning_prompt(self, theme: Dict[str, Any], app_type: str, screen_type: str) -> str:
"""Build prompt for Llama 3.1 to generate screen plan"""
theme_summary = {
"name": theme.get("name", ""),
"style": theme.get("style", ""),
"primary_color": theme.get("palette", {}).get("primary", "#007AFF"),
"typography": theme.get("typography", {}).get("display", {}).get("font_family", "System")
}
prompt = f"""You are an expert Flutter UI architect. Create a detailed plan for generating a {screen_type} screen for a {app_type} mobile app.
Theme Information:
- Name: {theme_summary['name']}
- Style: {theme_summary['style']}
- Primary Color: {theme_summary['primary_color']}
- Font: {theme_summary['typography']}
Task: Generate a JSON plan with appropriate components and layout for this screen.
Requirements:
1. Components must be relevant to {app_type} apps
2. Layout should match the {theme_summary['style']} style
3. Use Flutter Material 3 widgets
4. Include mock data structure
Output ONLY valid JSON in this format:
{{
"screen_type": "{screen_type}",
"layout": "column_scroll",
"sections": [
{{
"type": "appbar",
"component": "AppBar",
"params": {{"title": "...", "style": "..."}}
}},
{{
"type": "hero",
"component": "HeroBanner",
"params": {{"height": 200, "background": "gradient"}}
}}
],
"components": ["StatsCard", "FeatureGrid"],
"mock_data": {{
"user_name": "Marco Rossi",
"stats": {{"value1": 100, "value2": 200}}
}}
}}
JSON Plan:"""
return prompt
def _generate_variants_with_ai(self, theme: Dict[str, Any], app_type: str, custom_prompt: str = "") -> list:
"""
Use DeepSeek Coder to generate 4 intelligent UI variants
Each variant combines background + header + footer appropriately
"""
theme_summary = {
"name": theme.get("name", ""),
"style": theme.get("style", ""),
"primary": theme.get("palette", {}).get("primary", "#007AFF"),
"secondary": theme.get("palette", {}).get("secondary", "#5856D6")
}
# Get all background names for AI
bg_list = "\n".join([f"- {bg_id} ({info['name']}, {info['complexity']})" for bg_id, info in self.BACKGROUND_CATALOG.items()])
# Get card suggestions based on app type (only valid CARD_CATALOG IDs)
card_suggestions = {
"fitness": ["workout_exercise", "step_counter", "calorie_goal", "heart_rate", "achievement_badge", "weight_progress", "sleep_tracker", "water_intake", "nutrition_log"],
"banking": ["account_balance", "transaction_item", "credit_card", "transfer_form", "investment_item", "crypto_wallet", "bill_payment", "budget_category", "loan_summary"],
"rider": ["delivery_tracker", "map_location", "order_item", "message_preview", "stats_metric", "stats_progress", "leaderboard_entry", "achievement_badge"],
"ecommerce": ["product_vertical", "product_rating", "flash_sale", "cart_item", "wishlist_item", "product_grid_compact", "order_tracking", "offer_coupon", "brand_showcase"],
"social": ["social_post_card", "social_story_card", "profile_user_card", "comment_thread", "reaction_bar", "follower_item", "event_card", "poll_card", "notification_card"],
"generic": ["stats_metric", "task_item", "notification_card", "review_card", "article_card", "video_card", "stats_progress", "alert_card"]
}
cards_list = card_suggestions.get(app_type, card_suggestions["generic"])
cards_str = ", ".join(cards_list)
# Use custom prompt if provided, otherwise use default
task_description = custom_prompt if custom_prompt.strip() else f"Genera UNA home page per l'app {app_type}"
print(f"📝 Using prompt: {task_description}")
prompt = f"""TASK: {task_description}
Genera 4 VERSIONI DIVERSE usando questi componenti:
PALETTE COLORI:
- Primary: {theme_summary['primary']}
- Secondary: {theme_summary['secondary']}
- Style: {theme_summary['style']}
BACKGROUNDS disponibili (scegli 4 diversi):
{bg_list}
LAYOUTS disponibili (ogni variante DEVE usare un layout DIVERSO):
- grid_2x2: Griglia 2 colonne per metriche/dashboard
- vertical_list: Lista verticale scrollabile classica
- hero_card: UNA card grande in alto + 2-3 card piccole sotto
- timeline: Timeline verticale per eventi cronologici
HEADERS disponibili:
- minimal: Solo titolo pulito
- avatar_search: Avatar + barra ricerca (social apps)
- tabs: Tab orizzontali per navigazione
- stats_header: Mostra metriche chiave (fitness/finance apps)
FOOTERS disponibili:
- minimal_icons: Solo icone, nessuna label
- floating_fab: Bottone FAB centrale galleggiante
- animated_pills: Pill animate con transizioni smooth
- classic_expanded: Icone + etichette classiche
- gesture_bar: Barra gesture iOS-style
CARDS DISPONIBILI (SCEGLI 3-6 PER OGNI VARIANTE):
{cards_str}
REGOLE OBBLIGATORIE:
1. Ogni variante DEVE avere layout_type DIVERSO (grid_2x2, vertical_list, hero_card, timeline)
2. Ogni variante DEVE avere background DIVERSO
3. Ogni variante DEVE avere 3-6 CARDS dalla lista sopra
4. Le cards devono essere DIVERSE per ogni variante
5. I testi (header_title, header_subtitle) devono essere COERENTI con il TASK richiesto
ESEMPIO STRUTTURA JSON (USA CARDS DALLA LISTA SOPRA E TESTI COERENTI CON IL TASK!):
{{
"variants": [
{{
"name": "Nome Descrittivo Variante 1",
"description": "Breve descrizione",
"layout_type": "grid_2x2",
"background": "gradient_linear",
"header": "stats_header",
"footer": "minimal_icons",
"cards": ["card1", "card2", "card3", "card4"],
"texts": {{
"header_title": "Titolo COERENTE con il TASK",
"header_subtitle": "Sottotitolo opzionale",
"footer_labels": ["Tab1", "Tab2", "Tab3", "Tab4", "Tab5"]
}}
}},
{{
"name": "Nome Descrittivo Variante 2",
"description": "Approccio diverso",
"layout_type": "hero_card",
"background": "waves_smooth",
"header": "minimal",
"footer": "floating_fab",
"cards": ["card5", "card6", "card7"],
"texts": {{
"header_title": "Titolo DIVERSO ma COERENTE",
"header_subtitle": "",
"footer_labels": ["Home", "Explore", "Profile", "Settings", "More"]
}}
}},
...2 more variants (TOTAL 4) con layout_type, backgrounds e cards DIVERSI
]
}}
Output JSON:"""
try:
# Call DeepSeek API
print("🔍 DEBUG: Calling DeepSeek API...")
generated_text = self._call_deepseek_api(
messages=[{"role": "user", "content": prompt}],
max_tokens=800,
temperature=0.8
)
print(f"🔍 DEBUG: DeepSeek response received ({len(generated_text)} chars)")
result = self._extract_json_from_text(generated_text)
if result and "variants" in result:
variants = result["variants"][:4] # Max 4
print(f"✅ AI generated {len(variants)} variants from DeepSeek")
print(f"🔍 DEBUG: Variant names: {[v.get('name') for v in variants]}")
# DEBUG: Print cards for each variant
for v in variants:
cards = v.get('cards', [])
print(f"🔍 DEBUG: Variant '{v.get('name')}' has {len(cards)} cards: {cards}")
return variants
else:
print("⚠️ AI response invalid, using fallback")
return self._get_fallback_variants(app_type)
except Exception as e:
print(f"❌ AI variant generation error: {e}")
print("🔄 Using fallback variants instead")
return self._get_fallback_variants(app_type)
def _get_fallback_variants(self, app_type: str) -> list:
"""
Fallback variants if AI fails or no DEEPSEEK_API_KEY
Pre-configured smart combinations per app type
"""
fallback_map = {
"fitness": [
{
"name": "High Energy Action",
"description": "Dynamic design for active users",
"layout_type": "grid_2x2",
"background": "waves_smooth",
"header": "stats_header",
"footer": "floating_fab",
"cards": ["workout_exercise", "step_counter", "calorie_goal", "heart_rate"],
"texts": {
"header_title": "Workout Tracker",
"header_subtitle": "Today's Progress",
"footer_labels": ["Train", "Stats", "Goals", "Profile", "More"]
},
"reasoning": "Movement + always-visible stats + quick action"
},
{
"name": "Focus Mode",
"description": "Minimal UI during workout",
"layout_type": "hero_card",
"background": "gradient_linear",
"header": "minimal",
"footer": "gesture_bar",
"cards": ["workout_exercise", "heart_rate", "timer_widget"],
"texts": {
"header_title": "Active Session",
"header_subtitle": "",
"footer_labels": ["Home", "Activity", "Settings", "Profile", "Menu"]
},
"reasoning": "Clean gradient + minimal distractions"
},
{
"name": "Progress Dashboard",
"description": "Data-focused tracking",
"layout_type": "timeline",
"background": "geometric_circles",
"header": "tabs",
"footer": "animated_pills",
"cards": ["weight_progress", "achievement_badge", "sleep_tracker", "leaderboard_entry"],
"texts": {
"header_title": "Fitness Hub",
"header_subtitle": "Your Weekly Goals",
"footer_labels": ["Workouts", "Nutrition", "Progress", "Social", "More"]
},
"reasoning": "Geometric patterns + category navigation"
},
{
"name": "Gamified Tracker",
"description": "Playful achievement system",
"layout_type": "vertical_list",
"background": "abstract_particles",
"header": "avatar_search",
"footer": "classic_expanded",
"cards": ["achievement_badge", "stats_progress", "quest_card", "leaderboard_entry"],
"texts": {
"header_title": "Level Up",
"header_subtitle": "Achievements & Rewards",
"footer_labels": ["Challenges", "Leaderboard", "Rewards", "Friends", "Profile"]
},
"reasoning": "Particle effects = gamification + social features"
}
],
"banking": [
{
"name": "Trust & Security",
"description": "Professional and secure",
"background": "gradient_radial",
"header": "minimal",
"footer": "minimal_icons",
"cards": ["account_balance", "transaction_item", "credit_card", "stats_metric"],
"texts": {
"header_title": "My Accounts",
"header_subtitle": "Secure Banking",
"footer_labels": ["Home", "Payments", "Cards", "Account", "More"]
},
"reasoning": "Focus + trust + minimal distractions"
},
{
"name": "Financial Overview",
"description": "Organized account management",
"background": "gradient_linear",
"header": "tabs",
"footer": "classic_expanded",
"cards": ["transfer_form", "bill_payment", "investment_item", "budget_category"],
"texts": {
"header_title": "Financial Hub",
"header_subtitle": "Account Overview",
"footer_labels": ["Accounts", "Transfers", "Invest", "Budget", "Settings"]
},
"reasoning": "Clean + category tabs + clear navigation"
},
{
"name": "Premium Banking",
"description": "Elegant wealth management",
"background": "waves_minimal",
"header": "collapsible",
"footer": "animated_pills",
"cards": ["crypto_wallet", "investment_item", "stats_chart", "loan_summary"],
"texts": {
"header_title": "Wealth Manager",
"header_subtitle": "Premium Services",
"footer_labels": ["Portfolio", "Insights", "Advisory", "Profile", "Support"]
},
"reasoning": "Subtle motion + premium animations"
},
{
"name": "Modern Finance",
"description": "Contemporary digital banking",
"background": "pattern_lines",
"header": "avatar_search",
"footer": "gesture_bar",
"cards": ["budget_category", "stats_progress", "statement_month", "bill_payment"],
"texts": {
"header_title": "Smart Banking",
"header_subtitle": "Quick Actions",
"footer_labels": ["Dashboard", "Pay", "Save", "Rewards", "Menu"]
},
"reasoning": "Modern patterns + search + gestures"
}
],
"rider": [
{
"name": "Active Delivery",
"description": "On-the-go delivery tracking",
"background": "waves_sharp",
"header": "stats_header",
"footer": "floating_fab",
"cards": ["order_item", "delivery_tracker", "stats_metric", "message_preview"],
"texts": {
"header_title": "On Delivery",
"header_subtitle": "Today's Earnings",
"footer_labels": ["Orders", "Map", "Earnings", "Profile", "Help"]
},
"reasoning": "Movement + earnings visible + quick accept"
},
{
"name": "Map Focus",
"description": "Navigation-first design",
"background": "gradient_diagonal",
"header": "collapsible",
"footer": "minimal_icons",
"cards": ["map_location", "delivery_tracker", "timer_widget", "contact_card"],
"texts": {
"header_title": "Navigate",
"header_subtitle": "Active Route",
"footer_labels": ["Home", "Orders", "Map", "Stats", "Menu"]
},
"reasoning": "Clean map view + collapsing header"
},
{
"name": "Earnings Dashboard",
"description": "Income tracking focus",
"background": "abstract_crystalline",
"header": "tabs",
"footer": "classic_expanded",
"cards": ["stats_progress", "stats_metric", "stats_comparison", "stats_chart"],
"texts": {
"header_title": "Rider Hub",
"header_subtitle": "Weekly Performance",
"footer_labels": ["Dashboard", "Deliveries", "Income", "Rankings", "Settings"]
},
"reasoning": "Spotlight on earnings + clear navigation"
},
{
"name": "Social Rider",
"description": "Community and rankings",
"background": "geometric_stripes",
"header": "avatar_search",
"footer": "animated_pills",
"cards": ["leaderboard_entry", "profile_user_card", "quest_card", "achievement_badge"],
"texts": {
"header_title": "Rider Community",
"header_subtitle": "Leaderboard & Friends",
"footer_labels": ["Feed", "Challenges", "Leaderboard", "Friends", "Profile"]
},
"reasoning": "Playful + social features + leaderboard"
}
],
"ecommerce": [
{
"name": "Product Showcase",
"description": "Visual product gallery",
"background": "gradient_mesh",
"header": "avatar_search",
"footer": "floating_fab",
"cards": ["product_vertical", "product_rating", "flash_sale", "brand_showcase"],
"texts": {
"header_title": "Shop",
"header_subtitle": "Discover Products",
"footer_labels": ["Home", "Categories", "Cart", "Orders", "Account"]
},
"reasoning": "Rich visuals + search + quick cart access"
},
{
"name": "Clean Shopping",
"description": "Minimal product browsing",
"background": "pattern_dots",
"header": "minimal",
"footer": "classic_expanded",
"cards": ["product_grid_compact", "category_grid", "wishlist_item", "order_tracking"],
"texts": {
"header_title": "Store",
"header_subtitle": "Featured Collection",
"footer_labels": ["Browse", "Search", "Favorites", "Cart", "Profile"]
},
"reasoning": "Clean focus on products + clear navigation"
},
{
"name": "Premium Store",
"description": "Luxury shopping experience",
"background": "abstract_rays",
"header": "collapsible",
"footer": "animated_pills",
"cards": ["product_featured", "product_badge", "brand_showcase", "pricing_plan"],
"texts": {
"header_title": "Luxury Collection",
"header_subtitle": "Exclusive Items",
"footer_labels": ["Collections", "New Arrivals", "Wishlist", "VIP", "Profile"]
},
"reasoning": "Premium feel + smooth animations"
},
{
"name": "Dynamic Deals",
"description": "Engaging promotions",
"background": "waves_curved",
"header": "tabs",
"footer": "gesture_bar",
"cards": ["flash_sale", "offer_coupon", "cart_item", "order_summary"],
"texts": {
"header_title": "Flash Deals",
"header_subtitle": "Limited Time Offers",
"footer_labels": ["Deals", "Shop", "Cart", "Orders", "More"]
},
"reasoning": "Movement + category tabs + gestures"
}
],
"social": [
{
"name": "Community Feed",
"description": "Social content stream",
"background": "organic_fluid",
"header": "avatar_search",
"footer": "minimal_icons",
"cards": ["social_post_card", "social_story_card", "profile_user_card", "comment_thread"],
"texts": {
"header_title": "Feed",
"header_subtitle": "What's Happening",
"footer_labels": ["Home", "Explore", "Notifications", "Messages", "Profile"]
},
"reasoning": "Organic flow + search + simple navigation"
},
{
"name": "Stories Focus",
"description": "Ephemeral content first",
"background": "gradient_sweep",
"header": "minimal",
"footer": "gesture_bar",
"cards": ["social_story_card", "reel_preview", "live_streaming", "follower_item"],
"texts": {
"header_title": "Stories",
"header_subtitle": "24h Updates",
"footer_labels": ["Feed", "Stories", "Reels", "Live", "Menu"]
},
"reasoning": "Dynamic gradient + minimal UI + gestures"
},
{
"name": "Creator Platform",
"description": "Content creation tools",
"background": "geometric_hexagons",
"header": "tabs",
"footer": "floating_fab",
"cards": ["stats_chart", "video_card", "stats_progress", "notification_card"],
"texts": {
"header_title": "Create",
"header_subtitle": "Your Studio",
"footer_labels": ["Studio", "Content", "Analytics", "Community", "Profile"]
},
"reasoning": "Modern patterns + tools tabs + create button"
},
{
"name": "Activity Hub",
"description": "Notifications and updates",
"background": "abstract_constellation",
"header": "collapsible",
"footer": "animated_pills",
"cards": ["notification_card", "follower_item", "event_card", "poll_card"],
"texts": {
"header_title": "Activity",
"header_subtitle": "Your Network",
"footer_labels": ["Feed", "Activity", "Friends", "Groups", "More"]
},
"reasoning": "Connected dots + collapsing header + smooth nav"
}
]
}
# Default fallback for unknown app types
default_variants = [
{
"name": "Clean Minimal",
"background": "gradient_linear",
"header": "minimal",
"footer": "minimal_icons",
"cards": ["stats_metric", "task_item", "notification_card", "alert_card"],
"description": "Simple and clean",
"texts": {
"header_title": "Home",
"header_subtitle": "Welcome",
"footer_labels": ["Home", "Explore", "Search", "Settings", "Profile"]
},
"reasoning": "Minimal approach"
},
{
"name": "Dynamic Engaging",
"background": "waves_layered",
"header": "avatar_search",
"footer": "floating_fab",
"cards": ["article_card", "video_card", "stats_progress", "notification_card"],
"description": "Active and social",
"texts": {
"header_title": "Dashboard",
"header_subtitle": "Activity",
"footer_labels": ["Dashboard", "Activity", "Favorites", "Profile", "More"]
},
"reasoning": "Engaging design"
},
{
"name": "Modern Premium",
"background": "abstract_voronoi",
"header": "tabs",
"footer": "animated_pills",
"cards": ["pricing_plan", "review_card", "stats_chart", "offer_coupon"],
"description": "Professional look",
"texts": {
"header_title": "Overview",
"header_subtitle": "Premium",
"footer_labels": ["Overview", "Features", "Premium", "Account", "Settings"]
},
"reasoning": "Premium feel"
},
{
"name": "Creative Playful",
"background": "organic_blobs",
"header": "collapsible",
"footer": "classic_expanded",
"cards": ["video_card", "project_card", "article_card", "social_post_card"],
"description": "Fun and creative",
"texts": {
"header_title": "Creative Hub",
"header_subtitle": "Express Yourself",
"footer_labels": ["Create", "Gallery", "Explore", "Community", "Profile"]
},
"reasoning": "Playful design"
}
]
return fallback_map.get(app_type, default_variants)
def _generate_random_content(self, app_type: str, seed: int) -> Dict[str, Any]:
"""
Generate RANDOM variations of content (no AI needed)
Uses seed for reproducibility during testing
"""
import random
random.seed(seed)
# Variazioni per ogni app type
variations = {
"rider": {
"greetings": ["Ciao,", "Hey,", "Benvenuto,", "Buongiorno,"],
"subtitles": ["Pronto per consegnare?", "Inizia il tuo turno!", "Nuove consegne disponibili", "Zona attiva oggi"],
"main_card_titles": ["Prossima consegna", "Ordine in arrivo", "Nuova richiesta", "Consegna urgente"],
"main_texts": ["Ritiro pizza margherita", "Pacco da ritirare", "Ordine supermercato", "Consegna express"],
"main_details": ["Cliente Marco - Via Roma 21", "Distanza 2.3 km", "Paga alla consegna", "Consegna entro 15 min"],
"stat_labels": [
["Consegne", "Guadagno", "Km percorsi", "Rating"],
["Ordini", "Incasso", "Tempo attivo", "Stelle"],
["Corse", "€ oggi", "Ore online", "Feedback"],
],
"suggestions": [
("Zona calda!", "Molte richieste in centro ora"),
("Orario di punta", "Attiva il turno per guadagnare di più"),
("Percorso ottimale", "Risparmia 5 min unendo 2 consegne"),
],
"chart_titles": ["Guadagno settimanale", "Consegne per giorno", "Performance settimana", "Andamento €"],
"map_titles": ["Mappa consegne", "Zona di lavoro", "Area attiva", "Percorso oggi"],
"status_sets": [
["Online", "Pausa", "Supporto"],
["Disponibile", "Riposo", "Aiuto"],
["Attivo", "Offline", "Assistenza"],
]
},
"fitness": {
"greetings": ["Ciao,", "Hey,", "Forza,", "Bentornato,"],
"subtitles": ["Pronto ad allenarti?", "Nuovo workout disponibile", "Obiettivo giornaliero", "Inizia ora"],
"main_card_titles": ["Prossimo allenamento", "Workout del giorno", "Sfida attiva", "Sessione consigliata"],
"main_texts": ["HIIT 30 minuti", "Corsa mattutina", "Yoga serale", "Strength training"],
"main_details": ["Brucia 450 cal", "5 km in 30 min", "Relax e stretching", "Upper body focus"],
"stat_labels": [
["Calorie", "Passi", "Minuti attivi", "Obiettivo"],
["kcal bruciate", "Steps", "Workout time", "Target"],
["Energia", "Distanza", "Allenamenti", "Streak"],
],
"suggestions": [
("Sei vicino!", "Solo 500 passi al tuo obiettivo"),
("Momento perfetto", "Allenati ora per massimizzare energia"),
("Nuovo record", "Hai superato il tuo best settimanale!"),
],
"chart_titles": ["Calorie settimana", "Attività giornaliera", "Progress 7 giorni", "Trend fitness"],
"map_titles": ["Percorso corsa", "Tracciato attività", "Mappa allenamento", "Run map"],
"status_sets": [
["Attivo", "Riposo", "Aiuto"],
["Training", "Rest day", "Supporto"],
["On fire", "Pausa", "Info"],
]
},
"banking": {
"greetings": ["Benvenuto,", "Ciao,", "Buongiorno,", "Hey,"],
"subtitles": ["Gestisci il tuo denaro", "I tuoi conti", "Panoramica finanziaria", "Dashboard"],
"main_card_titles": ["Ultima transazione", "Movimento recente", "Operazione recente", "Pagamento"],
"main_texts": ["Pagamento Spotify", "Bonifico ricevuto", "Prelievo ATM", "Amazon acquisto"],
"main_details": ["-€9.99 • Oggi 14:32", "+€1.200 • Stipendio", "-€50.00 • Via Roma 15", "-€42.50 • Consegna prevista"],
"stat_labels": [
["Saldo", "Spese mese", "Risparmi", "Transazioni"],
["Disponibile", "Uscite", "Salvadanaio", "Movimenti"],
["Conto", "Budget usato", "Obiettivo", "Operazioni"],
],
"suggestions": [
("Risparmio smart", "Metti da parte €50 questo mese"),
("Spesa ridotta", "Hai speso -15% rispetto al mese scorso"),
("Nuovo obiettivo", "Crea un piano risparmio per le vacanze"),
],
"chart_titles": ["Spese settimana", "Bilancio 7 giorni", "Uscite recenti", "Trend mensile"],
"map_titles": ["ATM vicini", "Filiali", "Punti prelievo", "Sportelli area"],
"status_sets": [
["Principale", "Risparmio", "Aiuto"],
["Conto base", "Salvadanaio", "Supporto"],
["Attivo", "Investimenti", "Info"],
]
},
"ecommerce": {
"greetings": ["Ciao,", "Hey,", "Bentornato,", "Buongiorno,"],
"subtitles": ["Trova il prodotto perfetto", "Nuove offerte", "Scopri novità", "Shopping time"],
"main_card_titles": ["Offerta del giorno", "Deal speciale", "Sconto flash", "Promozione"],
"main_texts": ["iPhone 15 Pro -20%", "Scarpe Nike scontate", "Laptop Gaming", "Cuffie wireless"],
"main_details": ["€999 invece di €1.249", "Solo oggi -30%", "Prestazioni top", "Cancellazione rumore"],
"stat_labels": [
["Ordini", "Speso", "Punti", "Preferiti"],
["Acquisti", "Totale €", "Loyalty", "Wishlist"],
["Carrelli", "Budget", "Rewards", "Salvati"],
],
"suggestions": [
("Spedizione gratis", "Aggiungi €15 per sbloccare la spedizione"),
("Sconto attivo", "Usa il codice SAVE20 entro stasera"),
("Prodotto in sconto", "Un articolo della wishlist è scontato!"),
],
"chart_titles": ["Spese settimana", "Ordini 7 giorni", "Shopping trend", "Acquisti recenti"],
"map_titles": ["Negozi vicini", "Punti ritiro", "Store fisici", "Pickup points"],
"status_sets": [
["Shopping", "Wishlist", "Ordini"],
["Catalogo", "Preferiti", "Tracking"],
["Novità", "Salvati", "Storico"],
]
},
"social": {
"greetings": ["Ciao,", "Hey,", "Welcome back,", "Bentornato,"],
"subtitles": ["Cosa c'è di nuovo?", "Feed aggiornato", "Nuove storie", "Scopri"],
"main_card_titles": ["Post in evidenza", "Trending ora", "Hot topic", "Story del giorno"],
"main_texts": ["@marco_design nuovo post", "Video virale", "Foto travel goals", "Meme epico"],
"main_details": ["2.4k like • 340 commenti", "1.2M views", "145 condivisioni", "Trending #1"],
"stat_labels": [
["Post", "Follower", "Like", "Messaggi"],
["Contenuti", "Following", "Reactions", "Chat"],
["Stories", "Amici", "Engagement", "DM"],
],
"suggestions": [
("Nuovi follower", "5 persone hanno iniziato a seguirti"),
("Post virale", "Il tuo ultimo post ha 2k like!"),
("Amici attivi", "Marco e altri 12 sono online ora"),
],
"chart_titles": ["Engagement settimana", "Like ricevuti", "Attività 7 giorni", "Trend profilo"],
"map_titles": ["Amici vicini", "Check-in", "Luoghi taggati", "Mappa social"],
"status_sets": [
["Online", "Assente", "Invisibile"],
["Attivo", "Via", "Offline"],
["Disponibile", "Non disturbare", "Nascosto"],
]
}
}
# Get variations for this app type (or use generic)
app_vars = variations.get(app_type, variations["fitness"])
# Random selection
return {
"variant_id": seed,
"greeting": random.choice(app_vars["greetings"]),
"subtitle": random.choice(app_vars["subtitles"]),
"main_card_title": random.choice(app_vars["main_card_titles"]),
"main_card_text": random.choice(app_vars["main_texts"]),
"main_card_detail": random.choice(app_vars["main_details"]),
"stat_labels_set": random.choice(app_vars["stat_labels"]),
"suggestion": random.choice(app_vars["suggestions"]),
"chart_title": random.choice(app_vars["chart_titles"]),
"map_title": random.choice(app_vars["map_titles"]),
"status_labels": random.choice(app_vars["status_sets"])
}
def _generate_content_ideas(self, theme: Dict[str, Any], app_type: str) -> Dict[str, Any]:
"""
Use AI to generate DYNAMIC content ideas (texts, labels, titles)
Different from hardcoded templates!
"""
prompt = f"""You are a UX copywriter. Generate creative, varied content for a {app_type} mobile app home screen.
App Type: {app_type}
Theme: {theme.get("name", "Modern")}
Generate DIVERSE content ideas (not generic!). Output ONLY valid JSON:
{{
"greeting": "Ciao,",
"subtitle": "...",
"main_card_title": "...",
"main_card_text": "...",
"main_card_detail": "...",
"stat1_label": "...",
"stat2_label": "...",
"stat3_label": "...",
"stat4_label": "...",
"suggestion_title": "...",
"suggestion_text": "...",
"chart_title": "...",
"map_title": "...",
"status_labels": ["...", "...", "..."]
}}
Make it specific to {app_type} apps. Be creative and varied!
JSON:"""
try:
# Call DeepSeek API
generated_text = self._call_deepseek_api(
messages=[{"role": "user", "content": prompt}],
max_tokens=500,
temperature=0.9 # High temperature for variety
)
result = self._extract_json_from_text(generated_text)
if result:
print(f"✅ Generated dynamic content: {list(result.keys())}")
return result
else:
print("⚠️ Failed to extract JSON from AI response")
return {}
except Exception as e:
print(f"❌ Content generation error: {e}")
return {}
def _extract_json_from_text(self, text: str) -> Dict[str, Any]:
"""Extract JSON object from generated text"""
try:
# Try to find JSON in the text
start = text.find('{')
end = text.rfind('}') + 1
if start >= 0 and end > start:
json_str = text[start:end]
return json.loads(json_str)
except:
pass
return None
def _compile_screen(
self,
theme: Dict[str, Any],
app_type: str,
screen_type: str,
plan: Dict[str, Any]
) -> str:
"""
Use Jinja2 to compile Dart code from plan and theme
"""
# For now, generate inline since we don't have template files yet
# This will be replaced with actual Jinja2 templates
return self._generate_inline_dart(theme, app_type, screen_type, plan)
def _generate_background_only(
self,
theme: Dict[str, Any],
app_type: str,
bg_style: str
) -> str:
"""
Generate ONLY background with 4 style variations using theme colors
"""
palette = theme.get("palette", {})
# Extract colors from theme
primary = palette.get("primary", "#FF6D00").replace("#", "FF")
secondary = palette.get("secondary", "#FFE082").replace("#", "FF")
accent = palette.get("accent", "#FFA726").replace("#", "FF")
background = palette.get("background", "#FFF7F1").replace("#", "FF")
# Build minimal Dart code with ONLY background using router (supports all 30 backgrounds)
painter_code = self._get_background_painter(bg_style, primary, secondary, accent)
code = f'''import 'package:flutter/material.dart';
void main() {{
runApp(const MyApp());
}}
class MyApp extends StatelessWidget {{
const MyApp({{super.key}});
@override
Widget build(BuildContext context) {{
return MaterialApp(
title: 'Background Demo',
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
color: Colors.black,
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(32),
child: SizedBox(
width: 430,
height: 932,
child: CustomPaint(
painter: _BackgroundPainter(),
child: Column(
children: [
const SizedBox(height: 10),
const _FakeNotch(),
Expanded(
child: Container(),
),
],
),
),
),
),
),
),
),
);
}}
}}
/* ───────────────────────────── NOTCH FINTA ───────────────────────────── */
class _FakeNotch extends StatelessWidget {{
const _FakeNotch();
@override
Widget build(BuildContext context) {{
return Center(
child: Container(
width: 180,
height: 30,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.white.withOpacity(0.1),
width: 0.7,
),
),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 10,
height: 10,
decoration: const BoxDecoration(
color: Colors.black54,
shape: BoxShape.circle,
),
),
Container(
width: 70,
height: 4,
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(10),
),
),
const SizedBox(width: 10),
],
),
),
);
}}
}}
{painter_code}
'''
return code
def _get_waves_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── WAVES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()
..shader = LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0x{primary}).withOpacity(0.1),
Color(0x{secondary}).withOpacity(0.2),
Color(0x{accent}).withOpacity(0.1),
],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paintTop = Paint()
..color = Color(0x{primary}).withOpacity(0.4)
..style = PaintingStyle.fill;
final pathTop = Path()
..moveTo(0, size.height * 0.15)
..quadraticBezierTo(
size.width * 0.25,
size.height * 0.08,
size.width * 0.5,
size.height * 0.15,
)
..quadraticBezierTo(
size.width * 0.75,
size.height * 0.22,
size.width,
size.height * 0.14,
)
..lineTo(size.width, 0)
..lineTo(0, 0)
..close();
canvas.drawPath(pathTop, paintTop);
final paintMid = Paint()
..color = Color(0x{secondary}).withOpacity(0.35)
..style = PaintingStyle.fill;
final pathMid = Path()
..moveTo(0, size.height * 0.5)
..quadraticBezierTo(
size.width * 0.3,
size.height * 0.45,
size.width * 0.5,
size.height * 0.52,
)
..quadraticBezierTo(
size.width * 0.7,
size.height * 0.59,
size.width,
size.height * 0.5,
)
..lineTo(size.width, size.height * 0.3)
..lineTo(0, size.height * 0.3)
..close();
canvas.drawPath(pathMid, paintMid);
final paintBottom = Paint()
..color = Color(0x{accent}).withOpacity(0.3)
..style = PaintingStyle.fill;
final pathBottom = Path()
..moveTo(0, size.height * 0.88)
..quadraticBezierTo(
size.width * 0.25,
size.height * 0.82,
size.width * 0.5,
size.height * 0.86,
)
..quadraticBezierTo(
size.width * 0.75,
size.height * 0.91,
size.width,
size.height * 0.85,
)
..lineTo(size.width, size.height)
..lineTo(0, size.height)
..close();
canvas.drawPath(pathBottom, paintBottom);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_gradient_linear_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── LINEAR GRADIENT BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final paint = Paint()
..shader = LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0x{primary}),
Color(0x{secondary}),
Color(0x{accent}),
],
stops: [0.0, 0.5, 1.0],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_gradient_radial_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── RADIAL GRADIENT BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final paint = Paint()
..shader = RadialGradient(
center: Alignment.center,
radius: 1.0,
colors: [
Color(0x{primary}),
Color(0x{secondary}),
Color(0x{accent}),
],
stops: [0.0, 0.6, 1.0],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_geometric_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── GEOMETRIC BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
// Base gradient
final basePaint = Paint()
..shader = LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0x{primary}).withOpacity(0.2),
Color(0x{secondary}).withOpacity(0.3),
],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Large circle top left
final circlePaint1 = Paint()
..color = Color(0x{primary}).withOpacity(0.3)
..style = PaintingStyle.fill;
canvas.drawCircle(
Offset(size.width * 0.2, size.height * 0.15),
size.width * 0.4,
circlePaint1,
);
// Medium circle bottom right
final circlePaint2 = Paint()
..color = Color(0x{accent}).withOpacity(0.25)
..style = PaintingStyle.fill;
canvas.drawCircle(
Offset(size.width * 0.75, size.height * 0.7),
size.width * 0.35,
circlePaint2,
);
// Small circle center
final circlePaint3 = Paint()
..color = Color(0x{secondary}).withOpacity(0.2)
..style = PaintingStyle.fill;
canvas.drawCircle(
Offset(size.width * 0.5, size.height * 0.45),
size.width * 0.25,
circlePaint3,
);
// Rectangle top right
final rectPaint = Paint()
..color = Color(0x{accent}).withOpacity(0.15)
..style = PaintingStyle.fill;
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(
size.width * 0.6,
size.height * 0.1,
size.width * 0.3,
size.height * 0.2,
),
Radius.circular(20),
),
rectPaint,
);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
# ═══════════════════════════════════════════════════════════════════════
# GRADIENT BACKGROUNDS (6 total)
# ═══════════════════════════════════════════════════════════════════════
def _get_gradient_angular_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── ANGULAR GRADIENT BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final paint = Paint()
..shader = SweepGradient(
center: Alignment.center,
startAngle: 0.0,
endAngle: 6.28, // 2*PI
colors: [
Color(0x{primary}),
Color(0x{secondary}),
Color(0x{accent}),
Color(0x{primary}),
],
stops: [0.0, 0.33, 0.66, 1.0],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_gradient_sweep_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── SWEEP GRADIENT BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final paint = Paint()
..shader = SweepGradient(
center: Alignment(0.3, -0.5), // Offset center for dynamic effect
colors: [
Color(0x{primary}),
Color(0x{accent}),
Color(0x{secondary}),
Color(0x{primary}),
],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_gradient_mesh_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── MESH GRADIENT BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
// Create overlapping radial gradients for mesh effect
final gradient1 = Paint()
..shader = RadialGradient(
center: Alignment.topLeft,
radius: 1.5,
colors: [Color(0x{primary}), Colors.transparent],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
final gradient2 = Paint()
..shader = RadialGradient(
center: Alignment.topRight,
radius: 1.2,
colors: [Color(0x{secondary}), Colors.transparent],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height))
..blendMode = BlendMode.screen;
final gradient3 = Paint()
..shader = RadialGradient(
center: Alignment.bottomCenter,
radius: 1.0,
colors: [Color(0x{accent}), Colors.transparent],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height))
..blendMode = BlendMode.screen;
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), gradient1);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), gradient2);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), gradient3);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_gradient_diagonal_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── DIAGONAL GRADIENT BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final paint = Paint()
..shader = LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0x{primary}),
Color(0x{secondary}),
],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
# ═══════════════════════════════════════════════════════════════════════
# WAVE BACKGROUNDS (5 total)
# ═══════════════════════════════════════════════════════════════════════
def _get_waves_smooth_painter(self, primary: str, secondary: str, accent: str) -> str:
# This is the existing waves painter - keeping same implementation
return self._get_waves_painter(primary, secondary, accent)
def _get_waves_sharp_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── SHARP WAVES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()
..color = Color(0x{primary}).withOpacity(0.15);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Sharp zigzag wave 1
final paint1 = Paint()
..color = Color(0x{primary}).withOpacity(0.5)
..style = PaintingStyle.fill;
final path1 = Path()
..moveTo(0, size.height * 0.2);
for (double i = 0; i <= size.width; i += size.width / 8) {{
path1.lineTo(i, size.height * 0.15);
path1.lineTo(i + size.width / 16, size.height * 0.25);
}}
path1.lineTo(size.width, 0)..lineTo(0, 0)..close();
canvas.drawPath(path1, paint1);
// Sharp zigzag wave 2
final paint2 = Paint()
..color = Color(0x{secondary}).withOpacity(0.4)
..style = PaintingStyle.fill;
final path2 = Path()
..moveTo(0, size.height * 0.55);
for (double i = 0; i <= size.width; i += size.width / 10) {{
path2.lineTo(i, size.height * 0.5);
path2.lineTo(i + size.width / 20, size.height * 0.6);
}}
path2.lineTo(size.width, size.height * 0.35)..lineTo(0, size.height * 0.35)..close();
canvas.drawPath(path2, paint2);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_waves_layered_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── LAYERED WAVES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()
..shader = LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0x{primary}).withOpacity(0.1), Color(0x{accent}).withOpacity(0.1)],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Layer 1 - Bottom
final paint1 = Paint()..color = Color(0x{accent}).withOpacity(0.25);
final path1 = Path()
..moveTo(0, size.height * 0.7)
..quadraticBezierTo(size.width * 0.25, size.height * 0.65, size.width * 0.5, size.height * 0.72)
..quadraticBezierTo(size.width * 0.75, size.height * 0.79, size.width, size.height * 0.7)
..lineTo(size.width, size.height)..lineTo(0, size.height)..close();
canvas.drawPath(path1, paint1);
// Layer 2 - Middle
final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.3);
final path2 = Path()
..moveTo(0, size.height * 0.5)
..quadraticBezierTo(size.width * 0.3, size.height * 0.45, size.width * 0.5, size.height * 0.52)
..quadraticBezierTo(size.width * 0.7, size.height * 0.58, size.width, size.height * 0.5)
..lineTo(size.width, size.height)..lineTo(0, size.height)..close();
canvas.drawPath(path2, paint2);
// Layer 3 - Top
final paint3 = Paint()..color = Color(0x{primary}).withOpacity(0.35);
final path3 = Path()
..moveTo(0, size.height * 0.3)
..quadraticBezierTo(size.width * 0.25, size.height * 0.25, size.width * 0.5, size.height * 0.32)
..quadraticBezierTo(size.width * 0.75, size.height * 0.38, size.width, size.height * 0.3)
..lineTo(size.width, size.height)..lineTo(0, size.height)..close();
canvas.drawPath(path3, paint3);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_waves_curved_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── CURVED WAVES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Curved wave from top
final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.4);
final path1 = Path()
..moveTo(0, 0)
..lineTo(0, size.height * 0.2)
..cubicTo(size.width * 0.3, size.height * 0.1, size.width * 0.7, size.height * 0.3, size.width, size.height * 0.18)
..lineTo(size.width, 0)..close();
canvas.drawPath(path1, paint1);
// Curved wave from bottom
final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.35);
final path2 = Path()
..moveTo(0, size.height)
..lineTo(0, size.height * 0.75)
..cubicTo(size.width * 0.25, size.height * 0.85, size.width * 0.75, size.height * 0.65, size.width, size.height * 0.78)
..lineTo(size.width, size.height)..close();
canvas.drawPath(path2, paint2);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_waves_minimal_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── MINIMAL WAVE BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Single subtle wave
final paint = Paint()..color = Color(0x{secondary}).withOpacity(0.15);
final path = Path()
..moveTo(0, size.height * 0.4)
..quadraticBezierTo(size.width * 0.5, size.height * 0.35, size.width, size.height * 0.4)
..lineTo(size.width, size.height)
..lineTo(0, size.height)
..close();
canvas.drawPath(path, paint);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
# ═══════════════════════════════════════════════════════════════════════
# GEOMETRIC BACKGROUNDS (6 total)
# ═══════════════════════════════════════════════════════════════════════
def _get_geometric_circles_painter(self, primary: str, secondary: str, accent: str) -> str:
# This is the existing geometric painter - keeping same implementation
return self._get_geometric_painter(primary, secondary, accent)
def _get_geometric_triangles_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── TRIANGLE PATTERN BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Triangle 1 - Top
final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.3);
final path1 = Path()
..moveTo(size.width * 0.5, size.height * 0.05)
..lineTo(size.width * 0.2, size.height * 0.4)
..lineTo(size.width * 0.8, size.height * 0.4)
..close();
canvas.drawPath(path1, paint1);
// Triangle 2 - Left
final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.25);
final path2 = Path()
..moveTo(size.width * 0.1, size.height * 0.5)
..lineTo(size.width * 0.05, size.height * 0.8)
..lineTo(size.width * 0.35, size.height * 0.65)
..close();
canvas.drawPath(path2, paint2);
// Triangle 3 - Right
final paint3 = Paint()..color = Color(0x{accent}).withOpacity(0.28);
final path3 = Path()
..moveTo(size.width * 0.9, size.height * 0.6)
..lineTo(size.width * 0.65, size.height * 0.75)
..lineTo(size.width * 0.95, size.height * 0.85)
..close();
canvas.drawPath(path3, paint3);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_geometric_hexagons_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── HEXAGON GRID BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
void drawHexagon(Offset center, double radius, Color color) {{
final paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 2.0;
final path = Path();
for (int i = 0; i < 6; i++) {{
final angle = (3.14159 / 3) * i;
final x = center.dx + radius * cos(angle);
final y = center.dy + radius * sin(angle);
if (i == 0) {{
path.moveTo(x, y);
}} else {{
path.lineTo(x, y);
}}
}}
path.close();
canvas.drawPath(path, paint);
}}
// Draw hexagon grid
final hexSize = size.width * 0.15;
for (double row = 0; row < 8; row++) {{
for (double col = 0; col < 4; col++) {{
final x = col * hexSize * 1.8 + (row % 2) * hexSize * 0.9;
final y = row * hexSize * 0.9;
final colors = [
Color(0x{primary}).withOpacity(0.25),
Color(0x{secondary}).withOpacity(0.2),
Color(0x{accent}).withOpacity(0.22),
];
drawHexagon(Offset(x, y), hexSize * 0.5, colors[(row.toInt() + col.toInt()) % 3]);
}}
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}
import 'dart:math' show cos, sin;'''
def _get_geometric_grid_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── DOT GRID BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final dotPaint = Paint()..color = Color(0x{secondary}).withOpacity(0.3);
final spacing = size.width / 12;
for (double x = spacing; x < size.width; x += spacing) {{
for (double y = spacing; y < size.height; y += spacing) {{
canvas.drawCircle(Offset(x, y), 3.0, dotPaint);
}}
}}
// Accent dots
final accentPaint = Paint()..color = Color(0x{accent}).withOpacity(0.5);
for (double x = spacing * 3; x < size.width; x += spacing * 3) {{
for (double y = spacing * 3; y < size.height; y += spacing * 3) {{
canvas.drawCircle(Offset(x, y), 5.0, accentPaint);
}}
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_geometric_stripes_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── DIAGONAL STRIPES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paint1 = Paint()
..color = Color(0x{secondary}).withOpacity(0.25)
..style = PaintingStyle.fill;
final stripeWidth = size.width * 0.15;
for (double i = -size.height; i < size.width + size.height; i += stripeWidth * 2) {{
final path = Path()
..moveTo(i, 0)
..lineTo(i + stripeWidth, 0)
..lineTo(i + stripeWidth - size.height, size.height)
..lineTo(i - size.height, size.height)
..close();
canvas.drawPath(path, paint1);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_geometric_diamonds_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── DIAMOND SHAPES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
void drawDiamond(Offset center, double size, Color color) {{
final paint = Paint()..color = color;
final path = Path()
..moveTo(center.dx, center.dy - size)
..lineTo(center.dx + size, center.dy)
..lineTo(center.dx, center.dy + size)
..lineTo(center.dx - size, center.dy)
..close();
canvas.drawPath(path, paint);
}}
// Large diamond top-left
drawDiamond(
Offset(size.width * 0.25, size.height * 0.2),
size.width * 0.25,
Color(0x{primary}).withOpacity(0.25),
);
// Medium diamond center-right
drawDiamond(
Offset(size.width * 0.7, size.height * 0.5),
size.width * 0.18,
Color(0x{secondary}).withOpacity(0.22),
);
// Small diamond bottom-left
drawDiamond(
Offset(size.width * 0.3, size.height * 0.75),
size.width * 0.15,
Color(0x{accent}).withOpacity(0.28),
);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
# ═══════════════════════════════════════════════════════════════════════
# ORGANIC BACKGROUNDS (4 total)
# ═══════════════════════════════════════════════════════════════════════
def _get_organic_blobs_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── BLOB SHAPES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Blob 1
final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.25);
final path1 = Path()
..moveTo(size.width * 0.3, size.height * 0.15)
..cubicTo(size.width * 0.1, size.height * 0.2, size.width * 0.05, size.height * 0.35, size.width * 0.15, size.height * 0.45)
..cubicTo(size.width * 0.25, size.height * 0.55, size.width * 0.45, size.height * 0.5, size.width * 0.5, size.height * 0.35)
..cubicTo(size.width * 0.55, size.height * 0.2, size.width * 0.45, size.height * 0.1, size.width * 0.3, size.height * 0.15)
..close();
canvas.drawPath(path1, paint1);
// Blob 2
final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.22);
final path2 = Path()
..moveTo(size.width * 0.7, size.height * 0.6)
..cubicTo(size.width * 0.5, size.height * 0.65, size.width * 0.55, size.height * 0.8, size.width * 0.7, size.height * 0.85)
..cubicTo(size.width * 0.85, size.height * 0.9, size.width * 0.95, size.height * 0.75, size.width * 0.9, size.height * 0.6)
..cubicTo(size.width * 0.85, size.height * 0.55, size.width * 0.75, size.height * 0.57, size.width * 0.7, size.height * 0.6)
..close();
canvas.drawPath(path2, paint2);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_organic_fluid_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── FLUID EFFECT BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
// Smooth flowing shapes with gradients
final paint1 = Paint()
..shader = RadialGradient(
center: Alignment.topLeft,
radius: 1.2,
colors: [Color(0x{primary}), Color(0x{primary}).withOpacity(0.0)],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
final path1 = Path()
..moveTo(0, 0)
..cubicTo(size.width * 0.3, size.height * 0.1, size.width * 0.4, size.height * 0.3, size.width * 0.2, size.height * 0.5)
..cubicTo(size.width * 0.0, size.height * 0.7, 0, size.height * 0.4, 0, size.height * 0.5)
..lineTo(0, 0)
..close();
canvas.drawPath(path1, paint1);
final paint2 = Paint()
..shader = RadialGradient(
center: Alignment.bottomRight,
radius: 1.0,
colors: [Color(0x{secondary}), Color(0x{secondary}).withOpacity(0.0)],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
final path2 = Path()
..moveTo(size.width, size.height)
..cubicTo(size.width * 0.7, size.height * 0.9, size.width * 0.6, size.height * 0.7, size.width * 0.8, size.height * 0.5)
..cubicTo(size.width, size.height * 0.3, size.width, size.height * 0.6, size.width, size.height * 0.5)
..lineTo(size.width, size.height)
..close();
canvas.drawPath(path2, paint2);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_organic_noise_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── NOISE TEXTURE BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()
..shader = LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0x{primary}).withOpacity(0.2), Color(0x{secondary}).withOpacity(0.15)],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Simulated noise with random circles
final paint = Paint()..color = Color(0x{accent}).withOpacity(0.1);
final random = [0.1, 0.3, 0.5, 0.7, 0.9, 0.15, 0.35, 0.55, 0.75, 0.95];
for (int i = 0; i < 50; i++) {{
final x = size.width * random[i % 10];
final y = size.height * random[(i * 3) % 10];
final radius = 2.0 + (i % 5);
canvas.drawCircle(Offset(x, y), radius, paint);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_organic_clouds_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── CLOUD SHAPES BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
void drawCloud(Offset center, double scale, Color color) {{
final paint = Paint()..color = color;
// Cloud made of overlapping circles
canvas.drawCircle(Offset(center.dx, center.dy), 30 * scale, paint);
canvas.drawCircle(Offset(center.dx + 25 * scale, center.dy - 10 * scale), 35 * scale, paint);
canvas.drawCircle(Offset(center.dx + 50 * scale, center.dy), 28 * scale, paint);
canvas.drawCircle(Offset(center.dx + 25 * scale, center.dy + 10 * scale), 32 * scale, paint);
}}
drawCloud(Offset(size.width * 0.25, size.height * 0.2), 1.2, Color(0x{primary}).withOpacity(0.2));
drawCloud(Offset(size.width * 0.7, size.height * 0.35), 1.0, Color(0x{secondary}).withOpacity(0.18));
drawCloud(Offset(size.width * 0.4, size.height * 0.65), 0.9, Color(0x{accent}).withOpacity(0.16));
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
# ═══════════════════════════════════════════════════════════════════════
# PATTERN BACKGROUNDS (4 total)
# ═══════════════════════════════════════════════════════════════════════
def _get_pattern_dots_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── DOT PATTERN BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paint1 = Paint()..color = Color(0x{secondary}).withOpacity(0.25);
final paint2 = Paint()..color = Color(0x{accent}).withOpacity(0.2);
final spacing = size.width / 15;
for (double x = spacing; x < size.width; x += spacing) {{
for (double y = spacing; y < size.height; y += spacing) {{
final paint = ((x / spacing).toInt() + (y / spacing).toInt()) % 2 == 0 ? paint1 : paint2;
canvas.drawCircle(Offset(x, y), 4.0, paint);
}}
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_pattern_lines_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── LINE PATTERN BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paint = Paint()
..color = Color(0x{secondary}).withOpacity(0.25)
..strokeWidth = 2.0
..style = PaintingStyle.stroke;
final spacing = size.height / 20;
for (double y = 0; y < size.height; y += spacing) {{
canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_pattern_chevron_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── CHEVRON PATTERN BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paint1 = Paint()..color = Color(0x{secondary}).withOpacity(0.22);
final paint2 = Paint()..color = Color(0x{accent}).withOpacity(0.18);
final chevronHeight = size.height / 12;
for (double y = 0; y < size.height; y += chevronHeight * 2) {{
final paint = (y / (chevronHeight * 2)).toInt() % 2 == 0 ? paint1 : paint2;
final path = Path()
..moveTo(0, y)
..lineTo(size.width / 2, y + chevronHeight)
..lineTo(size.width, y)
..lineTo(size.width, y + chevronHeight * 2)
..lineTo(size.width / 2, y + chevronHeight * 3)
..lineTo(0, y + chevronHeight * 2)
..close();
canvas.drawPath(path, paint);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_pattern_zigzag_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── ZIGZAG PATTERN BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paint = Paint()
..color = Color(0x{secondary}).withOpacity(0.3)
..strokeWidth = 3.0
..style = PaintingStyle.stroke;
final spacing = size.height / 15;
for (double y = spacing; y < size.height; y += spacing) {{
final path = Path()..moveTo(0, y);
for (double x = 0; x < size.width; x += size.width / 10) {{
path.lineTo(x + size.width / 20, y - spacing / 2);
path.lineTo(x + size.width / 10, y);
}}
canvas.drawPath(path, paint);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
# ═══════════════════════════════════════════════════════════════════════
# ABSTRACT BACKGROUNDS (5 total)
# ═══════════════════════════════════════════════════════════════════════
def _get_abstract_crystalline_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── CRYSTALLINE BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paint1 = Paint()
..color = Color(0x{primary}).withOpacity(0.2)
..style = PaintingStyle.fill;
// Crystal facets
final paths = [
Path()
..moveTo(size.width * 0.3, size.height * 0.2)
..lineTo(size.width * 0.5, size.height * 0.1)
..lineTo(size.width * 0.6, size.height * 0.3)
..lineTo(size.width * 0.4, size.height * 0.4)
..close(),
Path()
..moveTo(size.width * 0.2, size.height * 0.5)
..lineTo(size.width * 0.4, size.height * 0.4)
..lineTo(size.width * 0.5, size.height * 0.6)
..lineTo(size.width * 0.3, size.height * 0.7)
..close(),
Path()
..moveTo(size.width * 0.6, size.height * 0.5)
..lineTo(size.width * 0.8, size.height * 0.4)
..lineTo(size.width * 0.9, size.height * 0.6)
..lineTo(size.width * 0.7, size.height * 0.7)
..close(),
];
final colors = [
Color(0x{primary}).withOpacity(0.25),
Color(0x{secondary}).withOpacity(0.22),
Color(0x{accent}).withOpacity(0.28),
];
for (int i = 0; i < paths.length; i++) {{
canvas.drawPath(paths[i], Paint()..color = colors[i]);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_abstract_voronoi_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── VORONOI DIAGRAM BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Simplified Voronoi cells
final cells = [
(Offset(size.width * 0.2, size.height * 0.2), Color(0x{primary}).withOpacity(0.2)),
(Offset(size.width * 0.7, size.height * 0.3), Color(0x{secondary}).withOpacity(0.18)),
(Offset(size.width * 0.5, size.height * 0.6), Color(0x{accent}).withOpacity(0.22)),
(Offset(size.width * 0.3, size.height * 0.75), Color(0x{primary}).withOpacity(0.15)),
(Offset(size.width * 0.8, size.height * 0.7), Color(0x{secondary}).withOpacity(0.2)),
];
for (final cell in cells) {{
final paint = Paint()..color = cell.$2;
final path = Path()
..addOval(Rect.fromCircle(center: cell.$1, radius: size.width * 0.25));
canvas.drawPath(path, paint);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_abstract_particles_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── PARTICLE FIELD BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Particle positions (pseudo-random but consistent)
final particles = [
(0.1, 0.2), (0.3, 0.15), (0.5, 0.25), (0.7, 0.18), (0.9, 0.22),
(0.15, 0.4), (0.35, 0.45), (0.55, 0.42), (0.75, 0.48), (0.85, 0.43),
(0.2, 0.6), (0.4, 0.65), (0.6, 0.62), (0.8, 0.68),
(0.25, 0.8), (0.45, 0.82), (0.65, 0.78), (0.85, 0.85),
];
final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.3);
final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.25);
final paint3 = Paint()..color = Color(0x{accent}).withOpacity(0.28);
final paints = [paint1, paint2, paint3];
// Draw particles
for (int i = 0; i < particles.length; i++) {{
final pos = particles[i];
final paint = paints[i % 3];
canvas.drawCircle(
Offset(size.width * pos.$1, size.height * pos.$2),
3.0 + (i % 4),
paint,
);
}}
// Draw connections
final linePaint = Paint()
..color = Color(0x{secondary}).withOpacity(0.15)
..strokeWidth = 1.0;
for (int i = 0; i < particles.length - 1; i++) {{
final p1 = particles[i];
final p2 = particles[i + 1];
canvas.drawLine(
Offset(size.width * p1.$1, size.height * p1.$2),
Offset(size.width * p2.$1, size.height * p2.$2),
linePaint,
);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
def _get_abstract_rays_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── LIGHT RAYS BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final center = Offset(size.width * 0.5, size.height * 0.3);
final paint = Paint()
..color = Color(0x{secondary}).withOpacity(0.15)
..style = PaintingStyle.fill;
// Radiating rays
for (double angle = 0; angle < 6.28; angle += 0.52) {{
final path = Path()
..moveTo(center.dx, center.dy)
..lineTo(
center.dx + size.width * cos(angle),
center.dy + size.height * sin(angle),
)
..lineTo(
center.dx + size.width * cos(angle + 0.26),
center.dy + size.height * sin(angle + 0.26),
)
..close();
canvas.drawPath(path, paint);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}
import 'dart:math' show cos, sin;'''
def _get_abstract_constellation_painter(self, primary: str, secondary: str, accent: str) -> str:
return f'''/* ────────────────────── STAR CONSTELLATION BACKGROUND ───────────────────────── */
class _BackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08);
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
// Star positions
final stars = [
(0.2, 0.2), (0.3, 0.25), (0.5, 0.18), (0.7, 0.22), (0.8, 0.3),
(0.25, 0.5), (0.4, 0.55), (0.6, 0.48), (0.75, 0.52),
(0.3, 0.75), (0.5, 0.8), (0.7, 0.78),
];
// Draw stars
final starPaint = Paint()..color = Color(0x{accent}).withOpacity(0.5);
for (final star in stars) {{
canvas.drawCircle(
Offset(size.width * star.$1, size.height * star.$2),
4.0,
starPaint,
);
}}
// Draw constellation lines
final linePaint = Paint()
..color = Color(0x{secondary}).withOpacity(0.25)
..strokeWidth = 1.5;
final connections = [(0, 1), (1, 2), (2, 3), (3, 4), (5, 6), (6, 7), (7, 8), (9, 10), (10, 11)];
for (final conn in connections) {{
final p1 = stars[conn.$1];
final p2 = stars[conn.$2];
canvas.drawLine(
Offset(size.width * p1.$1, size.height * p1.$2),
Offset(size.width * p2.$1, size.height * p2.$2),
linePaint,
);
}}
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}'''
# ═══════════════════════════════════════════════════════════════════════
# BACKGROUND ROUTER - Maps background IDs to painter functions
# ═══════════════════════════════════════════════════════════════════════
def _get_background_painter(self, bg_id: str, primary: str, secondary: str, accent: str) -> str:
"""Route background ID to correct painter function"""
painter_map = {
# GRADIENTS
"gradient_linear": self._get_gradient_linear_painter,
"gradient_radial": self._get_gradient_radial_painter,
"gradient_angular": self._get_gradient_angular_painter,
"gradient_sweep": self._get_gradient_sweep_painter,
"gradient_mesh": self._get_gradient_mesh_painter,
"gradient_diagonal": self._get_gradient_diagonal_painter,
# WAVES
"waves_smooth": self._get_waves_smooth_painter,
"waves_sharp": self._get_waves_sharp_painter,
"waves_layered": self._get_waves_layered_painter,
"waves_curved": self._get_waves_curved_painter,
"waves_minimal": self._get_waves_minimal_painter,
# GEOMETRIC
"geometric_circles": self._get_geometric_circles_painter,
"geometric_triangles": self._get_geometric_triangles_painter,
"geometric_hexagons": self._get_geometric_hexagons_painter,
"geometric_grid": self._get_geometric_grid_painter,
"geometric_stripes": self._get_geometric_stripes_painter,
"geometric_diamonds": self._get_geometric_diamonds_painter,
# ORGANIC
"organic_blobs": self._get_organic_blobs_painter,
"organic_fluid": self._get_organic_fluid_painter,
"organic_noise": self._get_organic_noise_painter,
"organic_clouds": self._get_organic_clouds_painter,
# PATTERNS
"pattern_dots": self._get_pattern_dots_painter,
"pattern_lines": self._get_pattern_lines_painter,
"pattern_chevron": self._get_pattern_chevron_painter,
"pattern_zigzag": self._get_pattern_zigzag_painter,
# ABSTRACT
"abstract_crystalline": self._get_abstract_crystalline_painter,
"abstract_voronoi": self._get_abstract_voronoi_painter,
"abstract_particles": self._get_abstract_particles_painter,
"abstract_rays": self._get_abstract_rays_painter,
"abstract_constellation": self._get_abstract_constellation_painter,
# Legacy aliases for backwards compatibility
"waves": self._get_waves_smooth_painter,
"geometric": self._get_geometric_circles_painter,
}
painter_func = painter_map.get(bg_id)
if painter_func:
return painter_func(primary, secondary, accent)
else:
# Fallback to gradient if unknown ID
print(f"⚠️ Unknown background ID '{bg_id}', using gradient_linear fallback")
return self._get_gradient_linear_painter(primary, secondary, accent)
def _generate_cards_code(
self,
cards: List[str],
theme_data: Dict[str, Any],
app_type: str
) -> str:
"""
Generate Dart code for multiple cards based on AI selection
Args:
cards: List of card IDs from variant (e.g., ["workout_summary", "step_counter"])
theme_data: Theme configuration with colors, fonts, etc.
app_type: App type for content personalization
Returns:
Dart code string with all card widgets
"""
if not cards:
# Fallback to generic cards if none specified
cards = ["info_card", "action_card", "feature_card"]
# Extract theme values for easy access
primary = theme_data["primary"]
secondary = theme_data["secondary"]
accent = theme_data["accent"]
surface = theme_data["surface_color"]
text_primary = theme_data["text_primary"]
text_secondary = theme_data["text_secondary"]
border_radius = theme_data["border_radius_medium"]
spacing = theme_data["spacing_unit"]
is_bold = theme_data["style"] == "bold"
cards_code_parts = []
# Content templates based on app type
content_templates = {
"fitness": {
"titles": ["Today's Workout", "Activity Ring", "Steps", "Calories", "Heart Rate", "Progress"],
"values": ["45 min", "85%", "8,420", "1,245 kcal", "72 bpm", "Week 3"],
"subtitles": ["Strength training", "Daily goal", "of 10,000", "burned today", "resting", "5 day streak"]
},
"banking": {
"titles": ["Account Balance", "Recent", "Transfer", "Investment", "Savings", "Budget"],
"values": ["$12,450", "$-85.50", "$500", "+12.5%", "$5,200", "78%"],
"subtitles": ["Main checking", "Starbucks Coffee", "Quick send", "This month", "Emergency fund", "Monthly limit"]
},
"rider": {
"titles": ["Today's Earnings", "Deliveries", "Rating", "Distance", "Online Time", "Bonus"],
"values": ["$145.50", "12", "4.8★", "45 km", "6.5 hrs", "+$25"],
"subtitles": ["8 hours", "Completed", "368 reviews", "Today", "Active", "Weekend bonus"]
},
"ecommerce": {
"titles": ["Flash Sale", "New Arrivals", "Top Rated", "Your Cart", "Wishlist", "Deals"],
"values": ["50% OFF", "Just In", "4.9★", "3 items", "12", "Limited"],
"subtitles": ["Ends in 2h", "Check now", "Bestseller", "$127.50", "Saved items", "Today only"]
},
"social": {
"titles": ["Your Story", "Messages", "Notifications", "Followers", "Engagement", "Trending"],
"values": ["+24", "5 new", "12", "1,245", "85%", "#Topic"],
"subtitles": ["Views today", "Unread", "New today", "This week", "Up 15%", "Popular now"]
}
}
templates = content_templates.get(app_type, content_templates["fitness"])
for idx, card_id in enumerate(cards):
# Get template content (cycle through if more cards than templates)
template_idx = idx % len(templates["titles"])
title = templates["titles"][template_idx]
value = templates["values"][template_idx]
subtitle = templates["subtitles"][template_idx]
# Determine accent color (rotate through theme colors)
if idx % 3 == 0:
accent_color = primary
elif idx % 3 == 1:
accent_color = secondary
else:
accent_color = accent
# Generate card widget based on catalog type
card_info = self.CARD_CATALOG.get(card_id, {})
card_complexity = card_info.get("complexity", "simple")
# Generate appropriate card based on complexity and type
if "stats" in card_id or "metric" in card_id or card_id in ["step_counter", "calorie_tracker", "heart_rate", "account_balance"]:
# Stats card with large number
card_code = f"""_StatsCard(
title: '{title}',
value: '{value}',
subtitle: '{subtitle}',
accentColor: Color(0x{accent_color}),
bgColor: Color(0x{surface}),
textColor: Color(0x{text_primary}),
subtitleColor: Color(0x{text_secondary}),
borderRadius: {border_radius}.0,
isBold: {str(is_bold).lower()},
)"""
elif "workout" in card_id or "exercise" in card_id or card_id in ["delivery_order", "order_item"]:
# Action card with progress/status
card_code = f"""_ActionCard(
title: '{title}',
status: '{value}',
description: '{subtitle}',
accentColor: Color(0x{accent_color}),
bgColor: Color(0x{surface}),
textColor: Color(0x{text_primary}),
subtitleColor: Color(0x{text_secondary}),
borderRadius: {border_radius}.0,
isBold: {str(is_bold).lower()},
)"""
elif "product" in card_id or "item" in card_id or card_id in ["flash_sale", "wishlist_item"]:
# Product/item card
card_code = f"""_ProductCard(
name: '{title}',
price: '{value}',
tag: '{subtitle}',
accentColor: Color(0x{accent_color}),
bgColor: Color(0x{surface}),
textColor: Color(0x{text_primary}),
subtitleColor: Color(0x{text_secondary}),
borderRadius: {border_radius}.0,
isBold: {str(is_bold).lower()},
)"""
else:
# Generic content card (fallback)
card_code = f"""_ContentCard(
title: '{title}',
subtitle: '{subtitle}',
accentColor: Color(0x{accent_color}),
bgColor: Color(0x{surface}),
textColor: Color(0x{text_primary}),
subtitleColor: Color(0x{text_secondary}),
borderRadius: {border_radius}.0,
borderWidth: 2.0,
isBold: {str(is_bold).lower()},
)"""
cards_code_parts.append(card_code)
# Join all cards with spacing
cards_with_spacing = f",\n SizedBox(height: {spacing * 2}.0),\n ".join(cards_code_parts)
return cards_with_spacing
def _generate_body_content(
self,
layout_type: str,
cards_code: str,
spacing_unit: int
) -> str:
"""
Generate body content layout based on layout_type
Args:
layout_type: grid_2x2, vertical_list, hero_card, timeline, featured_grid
cards_code: Pre-generated card widgets code
spacing_unit: Spacing value from theme
Returns:
Dart code for the Expanded body section
"""
layout_type = layout_type or "vertical_list" # Default
if layout_type == "grid_2x2":
# 2-column grid layout
return f"""Expanded(
child: Padding(
padding: EdgeInsets.all({spacing_unit * 2.5}),
child: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: {spacing_unit * 2.0},
mainAxisSpacing: {spacing_unit * 2.0},
childAspectRatio: 1.0,
children: [
{cards_code}
],
),
),
)"""
elif layout_type == "hero_card":
# One large hero card + smaller cards below
return f"""Expanded(
child: SingleChildScrollView(
padding: EdgeInsets.all({spacing_unit * 2.5}),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
{cards_code}
],
),
),
)"""
elif layout_type == "timeline":
# Vertical timeline layout
return f"""Expanded(
child: ListView(
padding: EdgeInsets.all({spacing_unit * 2.5}),
children: [
{cards_code}
],
),
)"""
else: # vertical_list (default) or featured_grid
# Classic vertical scrollable list
return f"""Expanded(
child: SingleChildScrollView(
padding: EdgeInsets.all({spacing_unit * 2.5}),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
{cards_code}
],
),
),
)"""
def _generate_complete_screen(
self,
theme: Dict[str, Any],
app_type: str,
variant: Dict[str, Any]
) -> str:
"""
Generate complete Flutter screen with background + header + footer
Based on AI-selected variant and FULL theme styles
"""
palette = theme.get("palette", {})
typography = theme.get("typography", {})
borders = theme.get("borders", {})
shadows = theme.get("shadows", {})
spacing = theme.get("spacing", {})
component_style = theme.get("component_style", {})
theme_style = theme.get("style", "modern") # bold, minimalist, elegant, etc.
# Extract ALL colors from palette
primary = palette.get("primary", "#FF6D00").replace("#", "FF")
secondary = palette.get("secondary", "#FFE082").replace("#", "FF")
accent = palette.get("accent", palette.get("warning", "#FFA726")).replace("#", "FF")
bg_color = palette.get("background", "#FFFFFF").replace("#", "FF")
surface_color = palette.get("surface", "#F5F5F5").replace("#", "FF")
text_primary = palette.get("text_primary", "#000000").replace("#", "FF")
text_secondary = palette.get("text_secondary", "#8E8E93").replace("#", "FF")
border_color = palette.get("border", "#E0E0E0").replace("#", "FF")
# Extract typography
display_font = typography.get("display", {}).get("font_family", "Roboto")
body_font = typography.get("body", {}).get("font_family", "Roboto")
numbers_font = typography.get("numbers", {}).get("font_family", body_font)
display_weight = typography.get("display", {}).get("weight", 700)
body_weight = typography.get("body", {}).get("weight", 400)
# Extract borders
border_radius_small = borders.get("radius", {}).get("small", "4px").replace("px", "")
border_radius_medium = borders.get("radius", {}).get("medium", "8px").replace("px", "")
border_radius_large = borders.get("radius", {}).get("large", "12px").replace("px", "")
border_width = borders.get("width", {}).get("regular", "2px").replace("px", "")
# Extract shadows (convert CSS to Flutter BoxShadow params)
shadow_medium = shadows.get("medium", "0 4px 8px rgba(0,0,0,0.25)")
# Extract spacing unit
spacing_unit = spacing.get("unit", 8)
# Create theme data object to pass to components
theme_data = {
"primary": primary,
"secondary": secondary,
"accent": accent,
"bg_color": bg_color,
"surface_color": surface_color,
"text_primary": text_primary,
"text_secondary": text_secondary,
"border_color": border_color,
"display_font": display_font,
"body_font": body_font,
"numbers_font": numbers_font,
"display_weight": display_weight,
"body_weight": body_weight,
"border_radius_small": border_radius_small,
"border_radius_medium": border_radius_medium,
"border_radius_large": border_radius_large,
"border_width": border_width,
"spacing_unit": spacing_unit,
"style": theme_style
}
# Get background painter using router (supports all 30 backgrounds)
bg_style = variant["background"]
painter_code = self._get_background_painter(bg_style, primary, secondary, accent)
# Extract theme values for use in Dart code generation
is_bold = (theme_style == "bold")
numbers_font = theme_data["numbers_font"]
# Get text customizations from variant
variant_texts = variant.get("texts", {})
# Get header code with theme data and text customizations
header_code = self._get_header_code(variant["header"], theme_data, app_type, variant_texts)
# Get footer code with theme data and text customizations
footer_code = self._get_footer_code(variant["footer"], theme_data, variant_texts)
# Generate dynamic cards from AI-selected card types
cards_list = variant.get("cards", [])
cards_code = self._generate_cards_code(cards_list, theme_data, app_type)
# Generate body content based on layout_type
layout_type = variant.get("layout_type", "vertical_list")
body_content = self._generate_body_content(layout_type, cards_code, spacing_unit)
# Build complete Dart code
code = f'''import 'package:flutter/material.dart';
void main() {{
runApp(const MyApp());
}}
class MyApp extends StatelessWidget {{
const MyApp({{super.key}});
@override
Widget build(BuildContext context) {{
return MaterialApp(
title: '{variant["name"]}',
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0x{primary}),
brightness: Brightness.light,
),
fontFamily: '{body_font}',
),
home: const HomePage(),
builder: (context, child) {{
return Container(
color: Colors.black,
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(32),
child: SizedBox(
width: 430,
height: 932,
child: child ?? const SizedBox(),
),
),
),
);
}},
);
}}
}}
class HomePage extends StatelessWidget {{
const HomePage({{super.key}});
@override
Widget build(BuildContext context) {{
return Scaffold(
backgroundColor: Colors.transparent,
body: CustomPaint(
painter: _BackgroundPainter(),
child: Column(
children: [
const SizedBox(height: 10),
const _FakeNotch(),
const SizedBox(height: 8),
{header_code},
{body_content}
],
),
),
{footer_code},
);
}}
}}
class _FakeNotch extends StatelessWidget {{
const _FakeNotch();
@override
Widget build(BuildContext context) {{
return Center(
child: Container(
width: 180,
height: 30,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.white.withOpacity(0.1),
width: 0.7,
),
),
),
);
}}
}}
// Helper widget for content cards (theme-aware)
class _ContentCard extends StatelessWidget {{
final String title;
final String subtitle;
final Color accentColor;
final Color bgColor;
final Color textColor;
final Color subtitleColor;
final double borderRadius;
final double borderWidth;
final bool isBold;
const _ContentCard({{
required this.title,
required this.subtitle,
required this.accentColor,
required this.bgColor,
required this.textColor,
required this.subtitleColor,
required this.borderRadius,
required this.borderWidth,
required this.isBold,
}});
@override
Widget build(BuildContext context) {{
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(borderRadius),
border: isBold ? Border.all(
color: accentColor.withOpacity(0.3),
width: borderWidth,
) : null,
boxShadow: [
BoxShadow(
color: isBold ? accentColor.withOpacity(0.2) : Colors.black.withOpacity(0.1),
blurRadius: isBold ? 12 : 8,
offset: Offset(0, isBold ? 6 : 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: isBold ? 6 : 4,
height: 40,
decoration: BoxDecoration(
color: accentColor,
borderRadius: BorderRadius.circular(isBold ? 3 : 2),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: isBold ? 20 : 18,
fontWeight: isBold ? FontWeight.w700 : FontWeight.w600,
color: textColor,
),
),
const SizedBox(height: 4),
Text(
subtitle,
style: TextStyle(
fontSize: 14,
color: subtitleColor,
),
),
],
),
),
],
),
],
),
);
}}
}}
// Stats Card Widget (for metrics and numbers)
class _StatsCard extends StatelessWidget {{
final String title;
final String value;
final String subtitle;
final Color accentColor;
final Color bgColor;
final Color textColor;
final Color subtitleColor;
final double borderRadius;
final bool isBold;
const _StatsCard({{
required this.title,
required this.value,
required this.subtitle,
required this.accentColor,
required this.bgColor,
required this.textColor,
required this.subtitleColor,
required this.borderRadius,
required this.isBold,
}});
@override
Widget build(BuildContext context) {{
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(borderRadius),
border: isBold ? Border.all(
color: accentColor.withOpacity(0.3),
width: 2,
) : null,
boxShadow: [
BoxShadow(
color: isBold ? accentColor.withOpacity(0.2) : Colors.black.withOpacity(0.1),
blurRadius: isBold ? 12 : 8,
offset: Offset(0, isBold ? 6 : 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: 14,
color: subtitleColor,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 8),
Text(
value,
style: TextStyle(
fontSize: isBold ? 36 : 32,
fontWeight: isBold ? FontWeight.w800 : FontWeight.w700,
color: accentColor,
),
),
const SizedBox(height: 4),
Text(
subtitle,
style: TextStyle(
fontSize: 13,
color: subtitleColor.withOpacity(0.7),
),
),
],
),
);
}}
}}
// Action Card Widget (for actions with status)
class _ActionCard extends StatelessWidget {{
final String title;
final String status;
final String description;
final Color accentColor;
final Color bgColor;
final Color textColor;
final Color subtitleColor;
final double borderRadius;
final bool isBold;
const _ActionCard({{
required this.title,
required this.status,
required this.description,
required this.accentColor,
required this.bgColor,
required this.textColor,
required this.subtitleColor,
required this.borderRadius,
required this.isBold,
}});
@override
Widget build(BuildContext context) {{
return Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(borderRadius),
border: isBold ? Border.all(
color: accentColor.withOpacity(0.3),
width: 2,
) : null,
boxShadow: [
BoxShadow(
color: isBold ? accentColor.withOpacity(0.2) : Colors.black.withOpacity(0.1),
blurRadius: isBold ? 12 : 8,
offset: Offset(0, isBold ? 6 : 4),
),
],
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: accentColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
Icons.flash_on_rounded,
color: accentColor,
size: 24,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: isBold ? 17 : 16,
fontWeight: isBold ? FontWeight.w700 : FontWeight.w600,
color: textColor,
),
),
const SizedBox(height: 4),
Text(
description,
style: TextStyle(
fontSize: 13,
color: subtitleColor,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: accentColor,
borderRadius: BorderRadius.circular(20),
),
child: Text(
status,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
),
],
),
);
}}
}}
// Product Card Widget (for items and products)
class _ProductCard extends StatelessWidget {{
final String name;
final String price;
final String tag;
final Color accentColor;
final Color bgColor;
final Color textColor;
final Color subtitleColor;
final double borderRadius;
final bool isBold;
const _ProductCard({{
required this.name,
required this.price,
required this.tag,
required this.accentColor,
required this.bgColor,
required this.textColor,
required this.subtitleColor,
required this.borderRadius,
required this.isBold,
}});
@override
Widget build(BuildContext context) {{
return Container(
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(borderRadius),
border: isBold ? Border.all(
color: accentColor.withOpacity(0.3),
width: 2,
) : null,
boxShadow: [
BoxShadow(
color: isBold ? accentColor.withOpacity(0.2) : Colors.black.withOpacity(0.1),
blurRadius: isBold ? 12 : 8,
offset: Offset(0, isBold ? 6 : 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 140,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [accentColor.withOpacity(0.3), accentColor.withOpacity(0.1)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.vertical(top: Radius.circular(borderRadius)),
),
child: Center(
child: Icon(
Icons.shopping_bag_rounded,
size: 48,
color: accentColor,
),
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
name,
style: TextStyle(
fontSize: isBold ? 17 : 16,
fontWeight: isBold ? FontWeight.w700 : FontWeight.w600,
color: textColor,
),
),
),
Text(
price,
style: TextStyle(
fontSize: isBold ? 18 : 16,
fontWeight: FontWeight.w700,
color: accentColor,
),
),
],
),
const SizedBox(height: 6),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: accentColor.withOpacity(0.15),
borderRadius: BorderRadius.circular(6),
),
child: Text(
tag,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: accentColor,
),
),
),
],
),
),
],
),
);
}}
}}
// Helper widget for tab items (used in tabs header)
class _TabItem extends StatelessWidget {{
final String label;
final bool isActive;
const _TabItem(this.label, this.isActive);
@override
Widget build(BuildContext context) {{
return Container(
margin: const EdgeInsets.only(right: 12),
padding: EdgeInsets.symmetric(horizontal: {spacing_unit * 2.5}, vertical: {spacing_unit * 1.25}),
decoration: BoxDecoration(
color: isActive ? Color(0x{primary}) : Colors.white.withOpacity(0.2),
borderRadius: BorderRadius.circular({border_radius_large}),
{("border: Border.all(color: Color(0x" + primary + "), width: " + str(border_width) + ")," if is_bold else "")}
),
child: Text(
label,
style: TextStyle(
fontFamily: '{display_font}',
color: Colors.white,
fontSize: {16 if is_bold else 14},
fontWeight: isActive ? FontWeight.{("w700" if is_bold else "w600")} : FontWeight.normal,
),
),
);
}}
}}
// Helper widget for stat items (used in stats_header)
class _StatItem extends StatelessWidget {{
final String value;
final String label;
const _StatItem(this.value, this.label);
@override
Widget build(BuildContext context) {{
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
value,
style: TextStyle(
fontFamily: '{numbers_font}',
fontSize: {32 if is_bold else 24},
fontWeight: FontWeight.{("w700" if is_bold else "w600")},
color: Colors.white,
),
),
SizedBox(height: {spacing_unit * 0.5}),
Text(
label,
style: TextStyle(
fontFamily: '{body_font}',
fontSize: {14 if is_bold else 12},
color: Colors.white.withOpacity(0.7),
),
),
],
);
}}
}}
// Helper widget for animated pills footer
class _NavPill extends StatelessWidget {{
final IconData icon;
final String label;
final bool isActive;
const _NavPill(this.icon, this.label, this.isActive);
@override
Widget build(BuildContext context) {{
return Container(
padding: EdgeInsets.symmetric(horizontal: {spacing_unit * 2}, vertical: {spacing_unit}),
decoration: BoxDecoration(
color: isActive ? Color(0x{primary}) : Colors.transparent,
borderRadius: BorderRadius.circular({border_radius_large}),
{("border: Border.all(color: Color(0x" + primary + ").withOpacity(0.3), width: " + str(border_width) + ")," if is_bold and not "isActive" else "")}
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: {26 if is_bold else 22},
color: isActive ? Colors.white : Color(0x{text_primary}).withOpacity(0.6),
),
if (isActive) ...[
SizedBox(width: {spacing_unit * 0.75}),
Text(
label,
style: TextStyle(
fontFamily: '{body_font}',
color: Colors.white,
fontSize: {15 if is_bold else 13},
fontWeight: FontWeight.{("w700" if is_bold else "w600")},
),
),
],
],
),
);
}}
}}
{painter_code}
'''
return code
def _get_header_code(self, header_type: str, theme_data: Dict[str, Any], app_type: str, texts: Dict[str, Any] = None) -> str:
"""Generate header widget code based on type and theme"""
# Extract text customizations or use defaults
if texts is None:
texts = {}
header_title = texts.get("header_title", app_type.capitalize())
header_subtitle = texts.get("header_subtitle", "Welcome")
primary = theme_data["primary"]
text_primary = theme_data["text_primary"]
display_font = theme_data["display_font"]
border_radius_medium = theme_data["border_radius_medium"]
spacing_unit = theme_data["spacing_unit"]
is_bold = theme_data["style"] == "bold"
headers = {
"minimal": f'''Container(
padding: EdgeInsets.all({spacing_unit * 2.5}),
child: Text(
'{header_title}',
style: TextStyle(
fontFamily: '{display_font}',
fontSize: {28 if is_bold else 24},
fontWeight: FontWeight.{("w700" if is_bold else "w600")},
color: Colors.white,
),
textAlign: TextAlign.center,
),
)''',
"avatar_search": f'''Container(
padding: EdgeInsets.symmetric(horizontal: {spacing_unit * 2.5}, vertical: {spacing_unit * 1.25}),
child: Row(
children: [
CircleAvatar(
radius: 20,
backgroundColor: Color(0x{primary}),
child: const Icon(Icons.person, color: Colors.white, size: 20),
),
const SizedBox(width: 12),
Expanded(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
borderRadius: BorderRadius.circular(24),
),
child: const Row(
children: [
Icon(Icons.search, color: Colors.white70, size: 20),
SizedBox(width: 8),
Text('Search...', style: TextStyle(color: Colors.white70)),
],
),
),
),
const SizedBox(width: 12),
Icon(Icons.notifications_none, color: Colors.white, size: 24),
],
),
)''',
"tabs": f'''Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(20),
child: Text(
'{header_title}',
style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white),
),
),
SizedBox(
height: 48,
child: ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 20),
children: [
_TabItem('Home', true),
_TabItem('Activity', false),
_TabItem('Profile', false),
],
),
),
],
)''',
"collapsible": f'''Container(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'{header_title}',
style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.white),
),
const SizedBox(height: 4),
Text(
'{header_subtitle}',
style: TextStyle(fontSize: 14, color: Colors.white.withOpacity(0.7)),
),
],
),
)''',
"stats_header": f'''Container(
padding: const EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_StatItem('24', 'Active'),
_StatItem('156', 'Total'),
_StatItem('4.8', 'Rating'),
],
),
)'''
}
return headers.get(header_type, headers["minimal"])
def _get_footer_code(self, footer_type: str, theme_data: Dict[str, Any], texts: Dict[str, Any] = None) -> str:
"""Generate footer navigation code based on type and theme"""
# Extract text customizations or use defaults
if texts is None:
texts = {}
footer_labels = texts.get("footer_labels", ["Home", "Search", "Favorites", "Profile", "Menu"])
primary = theme_data["primary"]
surface_color = theme_data["surface_color"]
text_primary = theme_data["text_primary"]
border_radius_large = theme_data["border_radius_large"]
spacing_unit = theme_data["spacing_unit"]
is_bold = theme_data["style"] == "bold"
footers = {
"minimal_icons": f'''bottomNavigationBar: Container(
margin: EdgeInsets.all({spacing_unit * 2}),
padding: EdgeInsets.symmetric(vertical: {spacing_unit * 1.5}),
decoration: BoxDecoration(
color: Color(0x{surface_color}),
borderRadius: BorderRadius.circular({border_radius_large}),
{("border: Border.all(color: Color(0x" + primary + ").withOpacity(0.2), width: 2)," if is_bold else "")}
boxShadow: [
BoxShadow(
color: Color(0x{primary}).withOpacity({0.15 if is_bold else 0.08}),
blurRadius: {10 if is_bold else 6},
offset: Offset(0, {4 if is_bold else 2}),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Icon(Icons.home, size: {32 if is_bold else 28}, color: Color(0x{primary})),
Icon(Icons.search, size: {32 if is_bold else 28}, color: Color(0x{text_primary}).withOpacity(0.6)),
Icon(Icons.favorite_border, size: {32 if is_bold else 28}, color: Color(0x{text_primary}).withOpacity(0.6)),
Icon(Icons.person_outline, size: {32 if is_bold else 28}, color: Color(0x{text_primary}).withOpacity(0.6)),
],
),
)''',
"floating_fab": f'''bottomNavigationBar: Container(
margin: const EdgeInsets.all(16),
height: 70,
child: Stack(
children: [
Container(
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.95),
borderRadius: BorderRadius.circular(24),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: const [
Icon(Icons.home, size: 28),
Icon(Icons.search, size: 28),
SizedBox(width: 60),
Icon(Icons.favorite_border, size: 28),
Icon(Icons.person_outline, size: 28),
],
),
),
Center(
child: FloatingActionButton(
onPressed: () {{}},
backgroundColor: Color(0x{primary}),
child: const Icon(Icons.add, size: 32),
),
),
],
),
)''',
"animated_pills": f'''bottomNavigationBar: Container(
margin: const EdgeInsets.all(16),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.95),
borderRadius: BorderRadius.circular(24),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_NavPill(Icons.home, 'Home', true),
_NavPill(Icons.search, 'Search', false),
_NavPill(Icons.favorite_border, 'Likes', false),
_NavPill(Icons.person_outline, 'Profile', false),
],
),
)''',
"classic_expanded": f'''bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedItemColor: Color(0x{primary}),
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
BottomNavigationBarItem(icon: Icon(Icons.favorite_border), label: 'Likes'),
BottomNavigationBarItem(icon: Icon(Icons.person_outline), label: 'Profile'),
],
)''',
"gesture_bar": f'''bottomNavigationBar: Container(
height: 34,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.95),
),
child: Center(
child: Container(
width: 134,
height: 5,
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadius.circular(3),
),
),
),
)'''
}
return footers.get(footer_type, footers["minimal_icons"])
def _generate_inline_dart(
self,
theme: Dict[str, Any],
app_type: str,
screen_type: str,
content_ideas: Dict[str, Any]
) -> str:
"""
Generate complex Dart code with Material 3, custom painters, charts, maps, etc.
Uses DYNAMIC content from AI, not hardcoded templates!
"""
palette = theme.get("palette", {})
typography = theme.get("typography", {})
spacing = theme.get("spacing", {})
# Extract colors
primary = palette.get("primary", "#FF6D00").replace("#", "FF")
secondary = palette.get("secondary", "#FFE082").replace("#", "FF")
background = palette.get("background", "#FFF7F1").replace("#", "FF")
# Generate light variations for gradients
primary_light = self._lighten_color(primary)
secondary_light = self._lighten_color(secondary)
# Extract typography
display_font = typography.get("display", {}).get("font_family", "Roboto")
body_font = typography.get("body", {}).get("font_family", "Roboto")
# Generate screen name
screen_class_name = f"{screen_type.capitalize()}Screen"
# Use RANDOM content variations
static_data = self._get_app_specific_data(app_type)
stat_labels = content_ideas.get("stat_labels_set", ["Val1", "Val2", "Val3", "Val4"])
suggestion = content_ideas.get("suggestion", ("Suggerimento", "Testo"))
app_data = {
"app_class": f"{app_type.capitalize()}App",
"title": f"{app_type.capitalize()} App",
"greeting": content_ideas.get("greeting", "Ciao,"),
"subtitle": content_ideas.get("subtitle", "Benvenuto!"),
"main_card_title": content_ideas.get("main_card_title", "Azione"),
"main_card_text": content_ideas.get("main_card_text", "Info"),
"main_card_detail": content_ideas.get("main_card_detail", "Dettagli"),
"stat1_label": stat_labels[0],
"stat1_value": static_data.get("stat1_value", "100"),
"stat1_icon": static_data.get("stat1_icon", "Icons.favorite_rounded"),
"stat2_label": stat_labels[1],
"stat2_value": static_data.get("stat2_value", "200"),
"stat2_icon": static_data.get("stat2_icon", "Icons.star_rounded"),
"stat3_label": stat_labels[2],
"stat3_value": static_data.get("stat3_value", "300"),
"stat3_icon": static_data.get("stat3_icon", "Icons.timer_rounded"),
"stat4_label": stat_labels[3],
"stat4_value": static_data.get("stat4_value", "400"),
"stat4_icon": static_data.get("stat4_icon", "Icons.flag_rounded"),
"suggestion_title": suggestion[0],
"suggestion_text": suggestion[1],
"chart_title": content_ideas.get("chart_title", "Grafico"),
"map_title": content_ideas.get("map_title", "Mappa"),
"status_labels": content_ideas.get("status_labels", ["A", "B", "C"])
}
user_name = "Utente"
# Build complex Dart code
code = f'''import 'package:flutter/material.dart';
void main() {{
runApp(const {app_data['app_class']}());
}}
class {app_data['app_class']} extends StatelessWidget {{
const {app_data['app_class']}({{super.key}});
@override
Widget build(BuildContext context) {{
return MaterialApp(
title: '{app_data['title']}',
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0x{primary}),
brightness: Brightness.light,
),
fontFamily: '{body_font}',
scaffoldBackgroundColor: const Color(0x{background}),
),
home: const {screen_class_name}(),
// 📱 MOCKUP iPhone + NOTCH + SFONDO WAVES
builder: (context, child) {{
return Container(
color: Colors.black,
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(32),
child: SizedBox(
width: 430,
height: 932,
child: CustomPaint(
painter: _WavesBackgroundPainter(),
child: Column(
children: [
const SizedBox(height: 10),
const _FakeNotch(),
const SizedBox(height: 8),
Expanded(
child: child ?? const SizedBox(),
),
],
),
),
),
),
),
);
}},
);
}}
}}
/* ──────────────────────────────── HOME PAGE ─────────────────────────────── */
class {screen_class_name} extends StatefulWidget {{
const {screen_class_name}({{super.key}});
@override
State<{screen_class_name}> createState() => _{screen_class_name}State();
}}
class _{screen_class_name}State extends State<{screen_class_name}> {{
int _currentTab = 0;
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
return Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
surfaceTintColor: Colors.transparent,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'{app_data['greeting']} {user_name} 👋',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: Colors.grey[900],
),
),
Text(
'{app_data['subtitle']}',
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey[700],
),
),
],
),
actions: [
IconButton(
onPressed: () {{}},
icon: const Icon(Icons.notifications_none_rounded),
),
],
),
body: _buildBody(theme),
bottomNavigationBar: Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: _BottomNavBar(
currentIndex: _currentTab,
onItemSelected: (index) {{
setState(() {{
_currentTab = index;
}});
}},
),
),
);
}}
Widget _buildBody(ThemeData theme) {{
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'{app_data['main_card_title']}',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[900],
),
),
const SizedBox(height: 12),
_MainActionCard(),
const SizedBox(height: 24),
Text(
'Oggi',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[900],
),
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _StatCard(
label: '{app_data['stat1_label']}',
value: '{app_data['stat1_value']}',
icon: {app_data['stat1_icon']},
tag: 'oggi',
),
),
const SizedBox(width: 12),
Expanded(
child: _StatCard(
label: '{app_data['stat2_label']}',
value: '{app_data['stat2_value']}',
icon: {app_data['stat2_icon']},
tag: 'oggi',
),
),
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _StatCard(
label: '{app_data['stat3_label']}',
value: '{app_data['stat3_value']}',
icon: {app_data['stat3_icon']},
tag: 'oggi',
),
),
const SizedBox(width: 12),
Expanded(
child: _StatCard(
label: '{app_data['stat4_label']}',
value: '{app_data['stat4_value']}',
icon: {app_data['stat4_icon']},
tag: 'totale',
),
),
],
),
const SizedBox(height: 24),
Text(
'Suggerimento',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[900],
),
),
const SizedBox(height: 12),
const _IllustrationCard(),
const SizedBox(height: 24),
Text(
'Andamento settimanale',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[900],
),
),
const SizedBox(height: 12),
const _ChartCard(),
const SizedBox(height: 24),
Text(
'{app_data['map_title']}',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[900],
),
),
const SizedBox(height: 8),
Text(
'Anteprima non interattiva - solo visualizzazione.',
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey[700],
),
),
const SizedBox(height: 12),
const _MapPreview(),
const SizedBox(height: 24),
Text(
'Stato',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[900],
),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_StatusChip(
label: '{app_data['status_labels'][0]}',
selected: true,
icon: Icons.radio_button_checked_rounded,
),
_StatusChip(
label: '{app_data['status_labels'][1]}',
selected: false,
icon: Icons.free_breakfast_rounded,
),
_StatusChip(
label: '{app_data['status_labels'][2]}',
selected: false,
icon: Icons.support_agent_rounded,
),
],
),
],
),
);
}}
}}
/* ───────────────────────────── NOTCH FINTA ───────────────────────────── */
class _FakeNotch extends StatelessWidget {{
const _FakeNotch();
@override
Widget build(BuildContext context) {{
return Center(
child: Container(
width: 180,
height: 30,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.white.withOpacity(0.1),
width: 0.7,
),
),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 10,
height: 10,
decoration: const BoxDecoration(
color: Colors.black54,
shape: BoxShape.circle,
),
),
Container(
width: 70,
height: 4,
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(10),
),
),
const SizedBox(width: 10),
],
),
),
);
}}
}}
/* ───────────────────── CARD AZIONE PRINCIPALE (MODERNA) ─────────────────── */
class _MainActionCard extends StatelessWidget {{
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFFFFF3E0),
Color(0xFFFFE0B2),
],
),
boxShadow: [
BoxShadow(
color: Colors.black12.withOpacity(0.05),
blurRadius: 18,
offset: const Offset(0, 10),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.8,
),
),
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.85),
borderRadius: BorderRadius.circular(999),
border: Border.all(
color: Colors.black.withOpacity(0.03),
width: 0.7,
),
),
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: theme.colorScheme.primary,
shape: BoxShape.circle,
),
),
const SizedBox(width: 6),
Text(
'Attivo',
style: theme.textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[800],
),
),
],
),
),
Row(
children: [
Icon(
Icons.access_time_rounded,
size: 16,
color: Colors.grey[800],
),
const SizedBox(width: 4),
Text(
'Ora',
style: theme.textTheme.labelMedium?.copyWith(
fontWeight: FontWeight.w500,
color: Colors.grey[900],
),
),
],
),
],
),
const SizedBox(height: 14),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 28,
height: 28,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.9),
shape: BoxShape.circle,
border: Border.all(
color: Colors.black.withOpacity(0.03),
width: 0.7,
),
),
child: Icon(
Icons.stars_rounded,
size: 18,
color: theme.colorScheme.primary,
),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'{app_data['main_card_text']}',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
color: Colors.grey[900],
),
),
const SizedBox(height: 4),
Text(
'{app_data['main_card_detail']}',
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey[700],
),
),
],
),
),
],
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: const [
_MiniInfoPill(
icon: Icons.info_outline_rounded,
label: 'Info 1',
),
SizedBox(width: 8),
_MiniInfoPill(
icon: Icons.check_circle_outline_rounded,
label: 'Info 2',
),
],
),
TextButton.icon(
onPressed: () {{}},
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
foregroundColor: Colors.grey[900],
),
icon: const Icon(Icons.arrow_forward_rounded, size: 18),
label: Text(
'Dettagli',
style: theme.textTheme.labelMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
),
],
),
],
),
);
}}
}}
class _MiniInfoPill extends StatelessWidget {{
final IconData icon;
final String label;
const _MiniInfoPill({{
required this.icon,
required this.label,
}});
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.9),
borderRadius: BorderRadius.circular(999),
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.7,
),
),
child: Row(
children: [
Icon(
icon,
size: 14,
color: theme.colorScheme.primary,
),
const SizedBox(width: 4),
Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.w500,
color: Colors.grey[800],
),
),
],
),
);
}}
}}
/* ───────────────────────────── STAT CARD MODERNA ─────────────────────────────── */
class _StatCard extends StatelessWidget {{
final String label;
final String value;
final IconData icon;
final String tag;
const _StatCard({{
required this.label,
required this.value,
required this.icon,
required this.tag,
}});
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFFFFFFFF),
Color(0xFFFFF3E0),
],
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.03),
blurRadius: 14,
offset: const Offset(0, 8),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.8,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: const Color(0xFFFFE0B2),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.7,
),
),
child: Icon(
icon,
size: 18,
color: theme.colorScheme.primary,
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(999),
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.7,
),
),
child: Text(
tag,
style: theme.textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[700],
),
),
),
],
),
const SizedBox(height: 10),
Text(
value,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w800,
color: Colors.grey[900],
),
),
const SizedBox(height: 4),
Text(
label,
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey[600],
),
),
],
),
);
}}
}}
/* ───────────────────────── ILLUSTRAZIONE FLAT CARD ─────────────────────── */
class _IllustrationCard extends StatelessWidget {{
const _IllustrationCard();
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFFFFFFFF),
Color(0xFFFFF0E3),
],
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.03),
blurRadius: 16,
offset: const Offset(0, 8),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.8,
),
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'{app_data['suggestion_title']}',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
color: Colors.grey[900],
),
),
const SizedBox(height: 6),
Text(
'{app_data['suggestion_text']}',
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey[700],
),
),
const SizedBox(height: 8),
Text(
'Suggerimento auto-generato',
style: theme.textTheme.labelSmall?.copyWith(
color: Colors.grey[600],
),
),
],
),
),
const SizedBox(width: 12),
SizedBox(
width: 88,
height: 88,
child: Stack(
alignment: Alignment.center,
children: [
Positioned(
top: 10,
child: Container(
width: 72,
height: 72,
decoration: BoxDecoration(
color: const Color(0xFFFFCC80),
shape: BoxShape.circle,
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.8,
),
),
),
),
Positioned(
bottom: 8,
child: Container(
width: 64,
height: 18,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.06),
borderRadius: BorderRadius.circular(20),
),
),
),
Positioned(
top: 20,
child: Icon(
Icons.lightbulb_outline_rounded,
size: 40,
color: theme.colorScheme.primary,
),
),
Positioned(
right: 4,
top: 8,
child: Container(
width: 18,
height: 18,
decoration: BoxDecoration(
color: const Color(0xFFFFF59D),
shape: BoxShape.circle,
border: Border.all(
color: Colors.black.withOpacity(0.05),
width: 0.7,
),
),
child: const Icon(
Icons.flash_on_rounded,
size: 14,
color: Colors.orange,
),
),
),
],
),
),
],
),
);
}}
}}
/* ───────────────────────── GRAFICO (BAR CHART) ───────────────────────────── */
class _ChartCard extends StatelessWidget {{
const _ChartCard();
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
final days = ['L', 'M', 'M', 'G', 'V', 'S', 'D'];
final heights = [40.0, 58.0, 32.0, 72.0, 64.0, 50.0, 80.0];
final selectedIndex = 6;
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFFFFFFFF),
Color(0xFFFFF3E0),
],
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.03),
blurRadius: 16,
offset: const Offset(0, 8),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.04),
width: 0.8,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'{app_data['chart_title']}',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
color: Colors.grey[900],
),
),
Text(
'Ultimi 7 giorni',
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.grey[600],
),
),
],
),
const SizedBox(height: 16),
SizedBox(
height: 90,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: List.generate(days.length, (index) {{
final isSelected = index == selectedIndex;
final h = heights[index];
return Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 250),
curve: Curves.easeOutQuad,
height: h,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(999),
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: isSelected
? [
Theme.of(context).colorScheme.primary,
const Color(0xFFFFE0B2),
]
: [
const Color(0xFFB0BEC5),
const Color(0xFFECEFF1),
],
),
border: Border.all(
color: Colors.black.withOpacity(0.03),
width: 0.6,
),
),
),
],
),
);
}}),
),
),
const SizedBox(height: 8),
Row(
children: List.generate(days.length, (index) {{
final isSelected = index == selectedIndex;
return Expanded(
child: Center(
child: Text(
days[index],
style: theme.textTheme.labelSmall?.copyWith(
fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500,
color: isSelected
? theme.colorScheme.primary
: Colors.grey[600],
),
),
),
);
}}),
),
],
),
);
}}
}}
/* ───────────────────────── MAPPA FINTA ────────────────────────── */
class _MapPreview extends StatelessWidget {{
const _MapPreview();
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
return Container(
height: 260,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFFFFF3E0),
Color(0xFFFFEBEE),
],
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.08),
blurRadius: 18,
offset: const Offset(0, 10),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.05),
width: 0.9,
),
),
child: Stack(
children: [
Positioned.fill(
child: CustomPaint(
painter: _MapRoadsPainter(),
),
),
const Positioned(
left: 40,
top: 60,
child: _MapMarker(
label: 'Punto A',
color: Colors.deepOrange,
icon: Icons.location_on_rounded,
),
),
const Positioned(
right: 40,
bottom: 70,
child: _MapMarker(
label: 'Punto B',
color: Colors.brown,
icon: Icons.flag_rounded,
),
),
Positioned(
left: 16,
right: 16,
top: 16,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.9),
borderRadius: BorderRadius.circular(999),
border: Border.all(
color: Colors.black.withOpacity(0.05),
width: 0.7,
),
),
child: Row(
children: [
Icon(Icons.route_rounded,
size: 18, color: theme.colorScheme.primary),
const SizedBox(width: 8),
Text(
'Percorso stimato 3.2 km • 9 min',
style: theme.textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.w500,
color: Colors.grey[800],
),
),
],
),
),
),
Positioned(
left: 16,
right: 16,
bottom: 16,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Mappa demo',
style: theme.textTheme.labelMedium?.copyWith(
color: Colors.grey[800],
),
),
Row(
children: [
Icon(Icons.zoom_in_map_rounded,
size: 18, color: Colors.grey[700]),
const SizedBox(width: 4),
Text(
'Non interattiva',
style: theme.textTheme.labelSmall?.copyWith(
color: Colors.grey[700],
),
),
],
),
],
),
),
],
),
);
}}
}}
class _MapMarker extends StatelessWidget {{
final String label;
final Color color;
final IconData icon;
const _MapMarker({{
required this.label,
required this.color,
required this.icon,
}});
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
return Column(
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.95),
borderRadius: BorderRadius.circular(999),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10,
offset: const Offset(0, 4),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.05),
width: 0.7,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 4),
Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.w600,
color: Colors.grey[900],
),
),
],
),
),
const SizedBox(height: 4),
Container(
width: 18,
height: 18,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: color.withOpacity(0.6),
blurRadius: 14,
offset: const Offset(0, 4),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.08),
width: 0.7,
),
),
),
],
);
}}
}}
class _MapRoadsPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final paintMain = Paint()
..color = Colors.white.withOpacity(0.9)
..style = PaintingStyle.stroke
..strokeWidth = 8
..strokeCap = StrokeCap.round;
final paintSecondary = Paint()
..color = Colors.white.withOpacity(0.7)
..style = PaintingStyle.stroke
..strokeWidth = 5
..strokeCap = StrokeCap.round;
final pathMain = Path()
..moveTo(size.width * 0.15, size.height * 0.2)
..quadraticBezierTo(
size.width * 0.4,
size.height * 0.1,
size.width * 0.65,
size.height * 0.3,
)
..quadraticBezierTo(
size.width * 0.9,
size.height * 0.5,
size.width * 0.7,
size.height * 0.8,
);
final pathSecondary = Path()
..moveTo(size.width * 0.05, size.height * 0.7)
..quadraticBezierTo(
size.width * 0.3,
size.height * 0.55,
size.width * 0.55,
size.height * 0.6,
)
..quadraticBezierTo(
size.width * 0.8,
size.height * 0.65,
size.width * 0.95,
size.height * 0.5,
);
canvas.drawPath(pathMain, paintMain);
canvas.drawPath(pathSecondary, paintSecondary);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}
/* ───────────────────────── STATUS CHIP ─────────────────────────────── */
class _StatusChip extends StatelessWidget {{
final String label;
final bool selected;
final IconData icon;
const _StatusChip({{
required this.label,
required this.selected,
required this.icon,
}});
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
final bgColor = selected
? theme.colorScheme.primary.withOpacity(0.12)
: Colors.white;
final borderColor = selected
? theme.colorScheme.primary
: Colors.grey[300]!;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(999),
color: bgColor,
border: Border.all(color: borderColor, width: 0.9),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: 18,
color: selected ? theme.colorScheme.primary : Colors.grey[700],
),
const SizedBox(width: 6),
Text(
label,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w500,
),
),
if (selected) ...[
const SizedBox(width: 4),
Container(
width: 6,
height: 6,
decoration: BoxDecoration(
color: theme.colorScheme.primary,
shape: BoxShape.circle,
),
),
]
],
),
);
}}
}}
/* ───────────────────────── BOTTOM NAV ANIMATA ─────────────────────── */
class _BottomNavBar extends StatelessWidget {{
final int currentIndex;
final ValueChanged<int> onItemSelected;
const _BottomNavBar({{
super.key,
required this.currentIndex,
required this.onItemSelected,
}});
@override
Widget build(BuildContext context) {{
final theme = Theme.of(context);
const items = [
_NavItemData(icon: Icons.home_rounded, label: 'Home'),
_NavItemData(icon: Icons.grid_view_rounded, label: 'Esplora'),
_NavItemData(icon: Icons.favorite_rounded, label: 'Preferiti'),
_NavItemData(icon: Icons.person_rounded, label: 'Profilo'),
];
return Container(
height: 64,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.96),
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.06),
blurRadius: 18,
offset: const Offset(0, 8),
),
],
border: Border.all(
color: Colors.black.withOpacity(0.05),
width: 0.9,
),
),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List.generate(items.length, (index) {{
final item = items[index];
final selected = index == currentIndex;
return _NavItem(
icon: item.icon,
label: item.label,
selected: selected,
onTap: () => onItemSelected(index),
theme: theme,
);
}}),
),
);
}}
}}
class _NavItemData {{
final IconData icon;
final String label;
const _NavItemData({{required this.icon, required this.label}});
}}
class _NavItem extends StatelessWidget {{
final IconData icon;
final String label;
final bool selected;
final VoidCallback onTap;
final ThemeData theme;
const _NavItem({{
required this.icon,
required this.label,
required this.selected,
required this.onTap,
required this.theme,
}});
@override
Widget build(BuildContext context) {{
return InkWell(
borderRadius: BorderRadius.circular(999),
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 220),
curve: Curves.easeOutQuad,
padding: EdgeInsets.symmetric(
horizontal: selected ? 16 : 10,
vertical: 8,
),
decoration: BoxDecoration(
color: selected
? theme.colorScheme.primary.withOpacity(0.10)
: Colors.transparent,
borderRadius: BorderRadius.circular(999),
border: Border.all(
color: selected
? theme.colorScheme.primary.withOpacity(0.3)
: Colors.transparent,
width: 0.9,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: 22,
color: selected ? theme.colorScheme.primary : Colors.grey[600],
),
if (selected) ...[
const SizedBox(width: 6),
Text(
label,
style: theme.textTheme.labelMedium?.copyWith(
fontWeight: FontWeight.w600,
color: theme.colorScheme.primary,
),
),
],
],
),
),
);
}}
}}
/* ────────────────────── SFONDO WAVES BACKGROUND ───────────────────────── */
class _WavesBackgroundPainter extends CustomPainter {{
@override
void paint(Canvas canvas, Size size) {{
final basePaint = Paint()
..shader = const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xFFFFF8F3),
Color(0xFFFFF0E3),
Color(0xFFFFF8F0),
],
).createShader(Rect.fromLTWH(0, 0, size.width, size.height));
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint);
final paintTop = Paint()
..color = const Color(0xFFFFCC80).withOpacity(0.55)
..style = PaintingStyle.fill;
final pathTop = Path()
..moveTo(0, size.height * 0.12)
..quadraticBezierTo(
size.width * 0.25,
size.height * 0.05,
size.width * 0.5,
size.height * 0.12,
)
..quadraticBezierTo(
size.width * 0.78,
size.height * 0.19,
size.width,
size.height * 0.11,
)
..lineTo(size.width, 0)
..lineTo(0, 0)
..close();
canvas.drawPath(pathTop, paintTop);
final paintMid = Paint()
..color = const Color(0xFFFFAB91).withOpacity(0.40)
..style = PaintingStyle.fill;
final pathMid = Path()
..moveTo(0, size.height * 0.45)
..quadraticBezierTo(
size.width * 0.25,
size.height * 0.40,
size.width * 0.5,
size.height * 0.46,
)
..quadraticBezierTo(
size.width * 0.78,
size.height * 0.52,
size.width,
size.height * 0.44,
)
..lineTo(size.width, size.height * 0.25)
..lineTo(0, size.height * 0.25)
..close();
canvas.drawPath(pathMid, paintMid);
final paintBottom = Paint()
..color = const Color(0xFFFFE082).withOpacity(0.38)
..style = PaintingStyle.fill;
final pathBottom = Path()
..moveTo(0, size.height * 0.85)
..quadraticBezierTo(
size.width * 0.2,
size.height * 0.78,
size.width * 0.45,
size.height * 0.83,
)
..quadraticBezierTo(
size.width * 0.75,
size.height * 0.89,
size.width,
size.height * 0.82,
)
..lineTo(size.width, size.height)
..lineTo(0, size.height)
..close();
canvas.drawPath(pathBottom, paintBottom);
}}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}}
'''
return code
def _lighten_color(self, hex_color: str) -> str:
"""Lighten a hex color (with FF prefix) for gradient effects"""
# Simple lightening: increase RGB values
if len(hex_color) != 8:
return hex_color
try:
r = int(hex_color[2:4], 16)
g = int(hex_color[4:6], 16)
b = int(hex_color[6:8], 16)
# Lighten by 30%
r = min(255, int(r + (255 - r) * 0.3))
g = min(255, int(g + (255 - g) * 0.3))
b = min(255, int(b + (255 - b) * 0.3))
return f"FF{r:02X}{g:02X}{b:02X}"
except:
return hex_color
def _get_app_specific_data(self, app_type: str) -> Dict[str, Any]:
"""Get app-specific data (titles, stats, icons) based on app type"""
app_configs = {
"rider": {
"app_class": "RiderApp",
"title": "Rider Demo",
"greeting": "Ciao,",
"subtitle": "Pronto per consegnare?",
"main_card_title": "Prossima consegna",
"stat1_label": "Consegne",
"stat1_value": "8",
"stat1_icon": "Icons.delivery_dining_rounded",
"stat2_label": "Guadagno",
"stat2_value": "€42,50",
"stat2_icon": "Icons.euro_rounded",
"stat3_label": "Tempo online",
"stat3_value": "03:18 h",
"stat3_icon": "Icons.access_time_rounded",
"stat4_label": "Rating",
"stat4_value": "4.9★",
"stat4_icon": "Icons.star_rate_rounded",
"map_title": "Mappa consegne"
},
"fitness": {
"app_class": "FitnessApp",
"title": "Fitness Tracker",
"greeting": "Ciao,",
"subtitle": "Pronto ad allenarti?",
"main_card_title": "Prossimo allenamento",
"stat1_label": "Calorie",
"stat1_value": "1.240",
"stat1_icon": "Icons.local_fire_department_rounded",
"stat2_label": "Passi",
"stat2_value": "8.542",
"stat2_icon": "Icons.directions_walk_rounded",
"stat3_label": "Tempo attivo",
"stat3_value": "02:15 h",
"stat3_icon": "Icons.timer_rounded",
"stat4_label": "Obiettivo",
"stat4_value": "85%",
"stat4_icon": "Icons.flag_rounded",
"map_title": "Percorso allenamento"
},
"banking": {
"app_class": "BankingApp",
"title": "Banking App",
"greeting": "Benvenuto,",
"subtitle": "Gestisci il tuo denaro",
"main_card_title": "Ultima transazione",
"stat1_label": "Saldo",
"stat1_value": "€3.420",
"stat1_icon": "Icons.account_balance_wallet_rounded",
"stat2_label": "Spese mese",
"stat2_value": "€1.240",
"stat2_icon": "Icons.trending_down_rounded",
"stat3_label": "Risparmi",
"stat3_value": "€5.680",
"stat3_icon": "Icons.savings_rounded",
"stat4_label": "Transazioni",
"stat4_value": "24",
"stat4_icon": "Icons.receipt_long_rounded",
"map_title": "ATM vicini"
},
"ecommerce": {
"app_class": "ShopApp",
"title": "Shop App",
"greeting": "Ciao,",
"subtitle": "Trova il prodotto perfetto",
"main_card_title": "Offerta del giorno",
"stat1_label": "Ordini",
"stat1_value": "12",
"stat1_icon": "Icons.shopping_bag_rounded",
"stat2_label": "Totale speso",
"stat2_value": "€420",
"stat2_icon": "Icons.euro_rounded",
"stat3_label": "Punti fedeltà",
"stat3_value": "1.240",
"stat3_icon": "Icons.loyalty_rounded",
"stat4_label": "Preferiti",
"stat4_value": "38",
"stat4_icon": "Icons.favorite_rounded",
"map_title": "Negozi vicini"
},
"social": {
"app_class": "SocialApp",
"title": "Social App",
"greeting": "Ciao,",
"subtitle": "Cosa c'è di nuovo?",
"main_card_title": "Post in evidenza",
"stat1_label": "Post",
"stat1_value": "142",
"stat1_icon": "Icons.post_add_rounded",
"stat2_label": "Follower",
"stat2_value": "1.2k",
"stat2_icon": "Icons.people_rounded",
"stat3_label": "Like ricevuti",
"stat3_value": "3.8k",
"stat3_icon": "Icons.favorite_rounded",
"stat4_label": "Messaggi",
"stat4_value": "24",
"stat4_icon": "Icons.chat_bubble_rounded",
"map_title": "Amici vicini"
}
}
return app_configs.get(app_type, app_configs["fitness"])
def _generate_simple_fallback(self, theme: Dict[str, Any], screen_type: str) -> str:
"""Generate simple fallback code when AI planning fails"""
return f'''import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {{
@override
Widget build(BuildContext context) {{
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('{screen_type.capitalize()}')),
body: Center(
child: Text('Screen: {screen_type}'),
),
),
);
}}
}}
'''
"""
AC3: Flutter Screen Generator Agent
Generates Flutter/Dart screen code using AI Planning (DeepSeek Coder) + Jinja2 templates.
Takes design themes from AC2 and generates runnable Dart code for DartPad.
"""
import os
import json
import requests
from typing import Dict, Any, List
from jinja2 import Environment, FileSystemLoader, select_autoescape
class FlutterScreenGenerator:
"""
Agent that generates Flutter screen code using AI planning and templates
"""
# BACKGROUND CATALOG - 30 unique variations
BACKGROUND_CATALOG = {
# GRADIENTS (6)
"gradient_linear": {"category": "gradients", "name": "Linear Gradient", "complexity": "simple"},
"gradient_radial": {"category": "gradients", "name": "Radial Gradient", "complexity": "simple"},
"gradient_angular": {"category": "gradients", "name": "Angular Gradient", "complexity": "medium"},
"gradient_sweep": {"category": "gradients", "name": "Sweep Gradient", "complexity": "medium"},
"gradient_mesh": {"category": "gradients", "name": "Mesh Gradient", "complexity": "complex"},
"gradient_diagonal": {"category": "gradients", "name": "Diagonal Gradient", "complexity": "simple"},
# WAVES (5)
"waves_smooth": {"category": "waves", "name": "Smooth Waves", "complexity": "medium"},
"waves_sharp": {"category": "waves", "name": "Sharp Waves", "complexity": "medium"},
"waves_layered": {"category": "waves", "name": "Layered Waves", "complexity": "complex"},
"waves_curved": {"category": "waves", "name": "Curved Waves", "complexity": "medium"},
"waves_minimal": {"category": "waves", "name": "Minimal Wave", "complexity": "simple"},
# GEOMETRIC (6)
"geometric_circles": {"category": "geometric", "name": "Floating Circles", "complexity": "medium"},
"geometric_triangles": {"category": "geometric", "name": "Triangle Pattern", "complexity": "medium"},
"geometric_hexagons": {"category": "geometric", "name": "Hexagon Grid", "complexity": "complex"},
"geometric_grid": {"category": "geometric", "name": "Dot Grid", "complexity": "simple"},
"geometric_stripes": {"category": "geometric", "name": "Diagonal Stripes", "complexity": "simple"},
"geometric_diamonds": {"category": "geometric", "name": "Diamond Shapes", "complexity": "medium"},
# ORGANIC (4)
"organic_blobs": {"category": "organic", "name": "Blob Shapes", "complexity": "complex"},
"organic_fluid": {"category": "organic", "name": "Fluid Effect", "complexity": "complex"},
"organic_noise": {"category": "organic", "name": "Noise Texture", "complexity": "medium"},
"organic_clouds": {"category": "organic", "name": "Cloud Shapes", "complexity": "medium"},
# PATTERNS (4)
"pattern_dots": {"category": "patterns", "name": "Dot Pattern", "complexity": "simple"},
"pattern_lines": {"category": "patterns", "name": "Line Pattern", "complexity": "simple"},
"pattern_chevron": {"category": "patterns", "name": "Chevron Pattern", "complexity": "medium"},
"pattern_zigzag": {"category": "patterns", "name": "Zigzag Pattern", "complexity": "medium"},
# ABSTRACT (5)
"abstract_crystalline": {"category": "abstract", "name": "Crystalline", "complexity": "complex"},
"abstract_voronoi": {"category": "abstract", "name": "Voronoi Diagram", "complexity": "complex"},
"abstract_particles": {"category": "abstract", "name": "Particle Field", "complexity": "medium"},
"abstract_rays": {"category": "abstract", "name": "Light Rays", "complexity": "medium"},
"abstract_constellation": {"category": "abstract", "name": "Star Constellation", "complexity": "medium"},
}
HEADER_CATALOG = {
# SOCIAL & PROFILE (5)
"profile_avatar_menu": {"name": "Profile Avatar Menu", "complexity": "medium", "description": "Avatar, username, location, menu"},
"avatar_notification_cart": {"name": "Avatar + Notifications + Cart", "complexity": "medium", "description": "User avatar, notification bell, shopping cart"},
"profile_stats_share": {"name": "Profile Stats Share", "complexity": "complex", "description": "Avatar, followers/following stats, share button"},
"social_search_filter": {"name": "Social Search Filter", "complexity": "medium", "description": "Search bar, filter icon, settings"},
"messenger_header": {"name": "Messenger Header", "complexity": "medium", "description": "Back button, user avatar, call/video icons"},
# LOCATION & DELIVERY (4)
"location_picker": {"name": "Location Picker", "complexity": "medium", "description": "GPS icon, current location, dropdown"},
"delivery_address_time": {"name": "Delivery Address + Time", "complexity": "complex", "description": "Address, delivery time estimate, change button"},
"map_search_location": {"name": "Map Search Location", "complexity": "medium", "description": "Search bar with GPS, current location"},
"ride_pickup_header": {"name": "Ride Pickup Header", "complexity": "complex", "description": "From/To locations, swap button"},
# E-COMMERCE (3)
"shop_cart_wishlist": {"name": "Shop Cart Wishlist", "complexity": "medium", "description": "Logo, search, wishlist, cart with badge"},
"category_filter_sort": {"name": "Category Filter Sort", "complexity": "medium", "description": "Category dropdown, filter, sort buttons"},
"product_search_scan": {"name": "Product Search Scan", "complexity": "medium", "description": "Search bar, barcode scan, voice search"},
# FINANCE & WALLET (3)
"wallet_balance_qr": {"name": "Wallet Balance QR", "complexity": "complex", "description": "Avatar, balance display, QR code button"},
"banking_accounts_menu": {"name": "Banking Accounts Menu", "complexity": "medium", "description": "Account selector, balance, menu"},
"crypto_portfolio_refresh": {"name": "Crypto Portfolio Refresh", "complexity": "medium", "description": "Total value, 24h change, refresh button"},
# HEALTH & FITNESS (2)
"fitness_streak_profile": {"name": "Fitness Streak Profile", "complexity": "complex", "description": "Avatar, streak counter, achievements"},
"workout_timer_pause": {"name": "Workout Timer Pause", "complexity": "medium", "description": "Timer display, pause/play, skip buttons"},
# MEDIA & ENTERTAINMENT (3)
"video_player_controls": {"name": "Video Player Controls", "complexity": "medium", "description": "Back, title, cast, more options"},
"music_player_header": {"name": "Music Player Header", "complexity": "simple", "description": "Back button, song title, artist, favorite"},
"news_category_tabs": {"name": "News Category Tabs", "complexity": "medium", "description": "Logo, category tabs, bookmark icon"},
}
FOOTER_CATALOG = {
# CLASSIC TAB BARS (6)