> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentsoflearning.com/llms.txt
> Use this file to discover all available pages before exploring further.

# BUILD OPTIMIZATION

# Build Optimization Guide

## Overview

This document provides instructions for building optimized release versions of the AI-Powered Photo Journaling app with maximum performance and minimal bundle size.

## Release Build Commands

### iOS Release Build (Optimized)

```bash theme={null}
flutter build ios --release \
  --tree-shake-icons \
  --split-debug-info=build/debug-info \
  --obfuscate \
  --dart-define-from-file=.env.production
```

### IPA Build for App Store

```bash theme={null}
flutter build ipa --release \
  --tree-shake-icons \
  --split-debug-info=build/debug-info \
  --obfuscate \
  --export-options-plist=ios/ExportOptions.plist
```

## Build Flags Explained

| Flag                      | Purpose                  | Impact                    |
| ------------------------- | ------------------------ | ------------------------- |
| `--release`               | Release mode compilation | Enables all optimizations |
| `--tree-shake-icons`      | Remove unused icons      | \~2-5 MB size reduction   |
| `--split-debug-info`      | Extract debug symbols    | \~10-15 MB size reduction |
| `--obfuscate`             | Obfuscate code           | Security + compression    |
| `--dart-define-from-file` | Environment variables    | Production config         |

## Build Configuration Files

### 1. Environment Files

Create `.env.production` for production builds:

```env theme={null}
# API Configuration
API_BASE_URL=https://api.overengineered.app
AI_PROVIDER=openai
OPENAI_MODEL=gpt-5
OPENAI_FALLBACK_MODEL=gpt-4-turbo

# Supabase Configuration
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key

# App Configuration
APP_ENV=production
ENABLE_ANALYTICS=true
ENABLE_DEBUG_LOGGING=false
```

### 2. Export Options (iOS)

Create `ios/ExportOptions.plist`:

```xml theme={null}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>method</key>
    <string>app-store</string>
    <key>teamID</key>
    <string>YOUR_TEAM_ID</string>
    <key>uploadBitcode</key>
    <false/>
    <key>compileBitcode</key>
    <true/>
    <key>uploadSymbols</key>
    <true/>
    <key>signingStyle</key>
    <string>automatic</string>
</dict>
</plist>
```

## Size Optimization Steps

### 1. Pre-Build Optimization

```bash theme={null}
# Clean previous builds
flutter clean

# Update dependencies
flutter pub get

# Analyze bundle size
flutter build ios --release --analyze-size
```

### 2. Asset Optimization

```bash theme={null}
# Compress images (requires ImageMagick)
find assets/images -name "*.jpg" -exec convert {} -quality 90 -resize 1920x1920\> {} \;
find assets/images -name "*.png" -exec convert {} -quality 90 -resize 1920x1920\> {} \;
```

### 3. Dependency Audit

```bash theme={null}
# List all dependencies and their sizes
flutter pub deps

# Check for unused dependencies
flutter pub outdated
```

### 4. Code Analysis

```bash theme={null}
# Run static analysis
flutter analyze

# Check for unused code
dart analyze --fatal-infos

# Format code
dart format .
```

## Performance Profiling

### 1. Profile Mode Build

```bash theme={null}
flutter build ios --profile
```

### 2. DevTools Profiling

```bash theme={null}
# Start DevTools
flutter pub global activate devtools
flutter pub global run devtools

# Run app in profile mode
flutter run --profile
```

### 3. Memory Profiling

Use the `MemoryProfiler` utility in debug mode:

```dart theme={null}
import 'package:app/core/utils/memory_profiler.dart';

// In main.dart
void main() {
  if (kDebugMode) {
    MemoryProfiler.startMonitoring();
    ImageCacheMonitor.optimizeCacheSettings();
  }
  runApp(MyApp());
}
```

## Expected Bundle Sizes

| Build Type            | Size        | Notes                               |
| --------------------- | ----------- | ----------------------------------- |
| Debug (unoptimized)   | \~80-100 MB | Full debug symbols, no optimization |
| Release (unoptimized) | \~50-60 MB  | Basic optimization only             |
| Release (optimized)   | \~20-30 MB  | All optimizations enabled           |
| App Store (device)    | \~15-20 MB  | With App Thinning                   |

## Build Scripts

### Automated Release Build

Create `scripts/build_release.sh`:

```bash theme={null}
#!/bin/bash

echo "🚀 Building optimized iOS release..."

# Clean
echo "🧹 Cleaning previous builds..."
flutter clean

# Get dependencies
echo "📦 Getting dependencies..."
flutter pub get

# Run tests
echo "🧪 Running tests..."
flutter test

# Analyze code
echo "🔍 Analyzing code..."
flutter analyze

# Build optimized IPA
echo "🏗️  Building optimized IPA..."
flutter build ipa --release \
  --tree-shake-icons \
  --split-debug-info=build/debug-info \
  --obfuscate \
  --dart-define-from-file=.env.production

echo "✅ Build complete!"
echo "📱 IPA location: build/ios/ipa/"
```

Make it executable:

```bash theme={null}
chmod +x scripts/build_release.sh
```

### Size Analysis Script

Create `scripts/analyze_size.sh`:

```bash theme={null}
#!/bin/bash

echo "📊 Analyzing bundle size..."

# Build with size analysis
flutter build ios --release --analyze-size > size_analysis.txt

# Extract app.so size
grep "app.so" size_analysis.txt

# Show breakdown
echo ""
echo "Full analysis saved to: size_analysis.txt"
```

## App Thinning (iOS)

Apple automatically applies App Thinning for App Store distributions:

1. **Slicing**: Delivers only assets for specific device
2. **Bitcode**: Allows Apple to recompile for new architectures
3. **On-Demand Resources**: Downloads resources when needed

Expected size reduction: **30-40%**

## Build Verification Checklist

Before submitting to App Store:

* [ ] All tests passing (`flutter test`)
* [ ] No analysis warnings (`flutter analyze`)
* [ ] Performance profiled in profile mode
* [ ] Memory leaks checked with MemoryProfiler
* [ ] Image cache optimized
* [ ] Bundle size \< 30 MB (pre-thinning)
* [ ] App launches in \< 2 seconds
* [ ] Timeline scrolls at 60 FPS
* [ ] No crashes in TestFlight
* [ ] All features working in release mode
* [ ] Analytics/error tracking configured
* [ ] Debug symbols uploaded

## Continuous Integration

### GitHub Actions Example

```yaml theme={null}
name: iOS Release Build

on:
  push:
    tags:
      - 'v*'

jobs:
  build:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v3

      - uses: subosito/flutter-action@v2
        with:
          flutter-version: '3.16.0'
          channel: 'stable'

      - name: Install dependencies
        run: flutter pub get

      - name: Run tests
        run: flutter test

      - name: Build IPA
        run: |
          flutter build ipa --release \
            --tree-shake-icons \
            --split-debug-info=build/debug-info \
            --obfuscate

      - name: Upload IPA
        uses: actions/upload-artifact@v3
        with:
          name: ios-release
          path: build/ios/ipa/*.ipa
```

## Troubleshooting

### Build Too Large

1. Check asset sizes: `find assets -type f -exec ls -lh {} \;`
2. Remove unused dependencies
3. Compress images
4. Use deferred loading for optional features

### Slow Build Times

1. Use `--analyze-size` to identify bottlenecks
2. Clean build folder: `flutter clean`
3. Update Flutter: `flutter upgrade`
4. Use `--no-tree-shake-icons` during development

### Obfuscation Issues

1. Check stack traces with mapping file
2. Disable obfuscation for debugging: remove `--obfuscate`
3. Keep symbols for crash reporting

## Resources

* [Flutter Performance Best Practices](https://docs.flutter.dev/perf/best-practices)
* [iOS App Thinning](https://developer.apple.com/documentation/xcode/reducing-your-app-s-size)
* [Flutter Build Modes](https://docs.flutter.dev/testing/build-modes)

***

**Last Updated**: 2025-11-15
**Maintained By**: Frontend Developer / DevOps Engineer
