chitfund/old_docs_backup_20251105_20.../FLUTTER_DEPLOYMENT_GUIDE.md

12 KiB

📱 Flutter Frontend Deployment Guide - LuckyChit

Complete guide to deploy and update your Flutter app UI changes in production.


📋 Deployment Options

Your Flutter app can be deployed as:

  1. Web App (accessible via browser)
  2. Android App (APK/AAB for Play Store)
  3. iOS App (IPA for App Store)

Initial Setup

Step 1: Build Flutter for Web

cd luckychit

# Clean previous builds
flutter clean

# Get dependencies
flutter pub get

# Build for production
flutter build web --release

This creates optimized files in luckychit/build/web/

Step 2: Deploy Web Files

Method A: Using nginx (Recommended)

# Copy built files to web server directory
sudo mkdir -p /var/www/luckychit
sudo cp -r build/web/* /var/www/luckychit/

# Set permissions
sudo chown -R www-data:www-data /var/www/luckychit
sudo chmod -R 755 /var/www/luckychit

Configure nginx:

Create/edit /etc/nginx/sites-available/luckychit:

server {
    listen 80;
    server_name your-domain.com;  # or your-server-ip

    # Flutter Web App
    location / {
        root /var/www/luckychit;
        index index.html;
        try_files $uri $uri/ /index.html;
        
        # Disable cache for index.html (always get latest)
        location = /index.html {
            add_header Cache-Control "no-cache, no-store, must-revalidate";
            add_header Pragma "no-cache";
            add_header Expires 0;
        }
        
        # Cache static assets for 1 year
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }

    # Backend API (if on same server)
    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}

Enable and restart nginx:

sudo ln -s /etc/nginx/sites-available/luckychit /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Method B: Using PM2 + http-server

# Install http-server globally
npm install -g http-server

# Start with PM2
cd luckychit
pm2 start http-server --name "luckychit-web" -- -p 8080 -c-1 -d false build/web

# Save
pm2 save

Method C: Using PM2 + Express (Custom Server)

Create luckychit/web-server.js:

const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 8080;

// Serve static files with proper cache headers
app.use(express.static(path.join(__dirname, 'build/web'), {
  maxAge: '1y',
  immutable: true,
  setHeaders: (res, filePath) => {
    // Don't cache index.html
    if (filePath.endsWith('index.html')) {
      res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
    }
  }
}));

// Handle Flutter routes (SPA)
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build/web', 'index.html'));
});

app.listen(PORT, '0.0.0.0', () => {
  console.log(`✅ Flutter web app running on port ${PORT}`);
});

Then:

cd luckychit
npm install express
pm2 start web-server.js --name "luckychit-web"
pm2 save

🔄 Updating Web App (How to Push Changes)

Quick Update Script

Create luckychit/deploy-web.sh:

#!/bin/bash

echo "🚀 Deploying Flutter Web Updates"
echo "================================="
echo ""

# Clean and build
echo "🧹 Cleaning previous build..."
flutter clean

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

echo "🔨 Building for web (production)..."
flutter build web --release

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ Build successful!"
    echo ""
    
    # Copy to nginx directory
    echo "📤 Deploying to web server..."
    sudo cp -r build/web/* /var/www/luckychit/
    
    # Or restart PM2 if using PM2
    # pm2 restart luckychit-web
    
    echo ""
    echo "✅ Deployment complete!"
    echo "🌐 Your app is now live with the latest changes!"
else
    echo ""
    echo "❌ Build failed. Please check errors above."
    exit 1
fi

Use it:

cd luckychit
chmod +x deploy-web.sh
./deploy-web.sh

📱 Option 2: Android Deployment

Build Android APK

For Testing:

cd luckychit

# Debug APK
flutter build apk --debug

# Release APK
flutter build apk --release

APK location: build/app/outputs/flutter-apk/app-release.apk

Build Android App Bundle (For Play Store)

cd luckychit

# Build release bundle
flutter build appbundle --release

Bundle location: build/app/outputs/bundle/release/app-release.aab

Deploy to Users

Method 1: Direct Distribution

# Copy APK to server
scp build/app/outputs/flutter-apk/app-release.apk user@server:/var/www/downloads/

# Users download and install from:
# https://your-domain.com/downloads/app-release.apk

Method 2: Google Play Store

  1. Sign in to Google Play Console
  2. Create app (if first time)
  3. Go to ReleaseProduction
  4. Click Create new release
  5. Upload app-release.aab
  6. Add release notes
  7. Review and rollout

Signing Android App (Required for Play Store)

Create keystore (first time only):

cd luckychit/android

keytool -genkey -v -keystore luckychit-key.jks \
  -keyalg RSA -keysize 2048 -validity 10000 \
  -alias luckychit

Create android/key.properties:

storePassword=your_keystore_password
keyPassword=your_key_password
keyAlias=luckychit
storeFile=/path/to/luckychit-key.jks

Update android/app/build.gradle:

// Add before android block
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    // ... existing config ...
    
    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
}

Now build:

flutter build appbundle --release

🍎 Option 3: iOS Deployment

Build iOS App

cd luckychit

# Build for iOS
flutter build ios --release

Deploy to App Store

  1. Open Xcode: open ios/Runner.xcworkspace
  2. Select ProductArchive
  3. Once archived, click Distribute App
  4. Choose App Store Connect
  5. Follow the upload wizard

Or use command line:

cd ios
fastlane deliver

🚀 Production Update Workflow

For Web (Quickest)

# On your development machine
cd luckychit
flutter build web --release

# Upload to server
scp -r build/web/* user@server:/tmp/flutter-web/

# On server
ssh user@server
sudo cp -r /tmp/flutter-web/* /var/www/luckychit/
# Or if using PM2:
# pm2 restart luckychit-web

For Mobile Apps

  1. Make changes in your code
  2. Update version in pubspec.yaml:
    version: 1.0.1+2  # version+buildNumber
    
  3. Build:
    # Android
    flutter build appbundle --release
    
    # iOS
    flutter build ios --release
    
  4. Upload to stores

🔧 Common Issues & Solutions

Web App Not Updating (Cache Issues)

Problem: Users still see old version

Solution 1: Force reload

  • Chrome: Ctrl+Shift+R (Windows) or Cmd+Shift+R (Mac)
  • Clear browser cache

Solution 2: Update index.html cache headers

Edit luckychit/web/index.html - add to <head>:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

Solution 3: Version your assets

Update pubspec.yaml:

version: 1.0.1+2  # Increment this

Rebuild:

flutter clean
flutter pub get
flutter build web --release

Android Build Fails

Common issues:

  1. Gradle version mismatch:

    cd android
    ./gradlew clean
    cd ..
    flutter clean
    flutter build apk
    
  2. Signing issues:

    • Check key.properties exists and paths are correct
    • Verify keystore password
  3. Memory issues:

    export GRADLE_OPTS="-Xmx4096m"
    flutter build apk --release
    

iOS Build Fails

  1. Pod issues:

    cd ios
    rm Podfile.lock
    pod install
    cd ..
    flutter build ios
    
  2. Provisioning profile:

    • Update in Xcode → Signing & Capabilities

📦 Automated Deployment Scripts

Complete Web Deployment Script

Create flutter-deploy-full.sh:

#!/bin/bash

# LuckyChit Flutter Web Deployment Script
# Run from project root

SERVER_USER="your-user"
SERVER_HOST="your-server-ip"
WEB_DIR="/var/www/luckychit"

echo "🚀 LuckyChit Flutter Web Deployment"
echo "===================================="
echo ""

# Build
cd luckychit
echo "🧹 Cleaning..."
flutter clean

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

echo "🔨 Building for web..."
flutter build web --release

if [ $? -ne 0 ]; then
    echo "❌ Build failed!"
    exit 1
fi

echo "✅ Build successful!"
echo ""

# Upload to server
echo "📤 Uploading to production server..."
rsync -avz --delete build/web/ $SERVER_USER@$SERVER_HOST:$WEB_DIR/

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ Deployment complete!"
    echo "🌐 Your app is now live!"
    echo ""
    echo "Clear browser cache (Ctrl+Shift+R) to see changes"
else
    echo "❌ Upload failed!"
    exit 1
fi

Android Auto-Build Script

Create luckychit/build-android.sh:

#!/bin/bash

echo "🤖 Building Android Release"
echo "============================"
echo ""

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

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

# Build
echo "🔨 Building APK..."
flutter build apk --release

echo "🔨 Building App Bundle..."
flutter build appbundle --release

echo ""
echo "✅ Build complete!"
echo ""
echo "📦 APK: build/app/outputs/flutter-apk/app-release.apk"
echo "📦 AAB: build/app/outputs/bundle/release/app-release.aab"
echo ""
echo "Upload AAB to Google Play Console"

📊 Version Management

Update Version in pubspec.yaml

name: luckychit
description: Digital Chit Fund Management
version: 1.0.2+3  # Format: major.minor.patch+buildNumber

# Increment for each release:
# - major: Breaking changes (2.0.0)
# - minor: New features (1.1.0)
# - patch: Bug fixes (1.0.1)
# - buildNumber: Each build (1.0.0+5)

Check Current Version

cd luckychit
grep "^version:" pubspec.yaml

Deployment Checklist

Before Deploying

  • All changes tested locally
  • Version incremented in pubspec.yaml
  • Backend API URL updated (if changed)
  • flutter clean executed
  • flutter pub get executed
  • Build completed successfully
  • No errors in console

After Deploying

  • Web: Files copied to /var/www/luckychit/
  • Web: nginx restarted (if needed)
  • Test app in browser (hard refresh)
  • Test on mobile device (if mobile build)
  • Check all features work
  • Monitor for errors

🎯 Quick Reference

# Clean build
flutter clean && flutter pub get

# Web (production)
flutter build web --release

# Android APK
flutter build apk --release

# Android Bundle (Play Store)
flutter build appbundle --release

# iOS
flutter build ios --release

# Check version
grep "^version:" pubspec.yaml

📱 Testing Builds

Web

cd luckychit/build/web
python3 -m http.server 8000
# Visit: http://localhost:8000

Android

# Install on connected device
flutter install

# Or manually install APK
adb install build/app/outputs/flutter-apk/app-release.apk

Your Flutter frontend is now ready to deploy and update! 🎉

For backend updates, see: PM2_PRODUCTION_GUIDE.md