Flutter: Project Deployment — ShopApp Launch and Release
Launch is not the end — it's the starting point of continuous delivery.
📋 Prerequisites: You should have mastered the following first
1. What You Will Learn
- Build optimization: Tree Shaking / code splitting / asset compression / R8 obfuscation
- Android deployment: signing key + App Bundle + Google Play publishing
- iOS deployment: certificate configuration + TestFlight + App Store review
- Web deployment: Firebase Hosting + PWA + SEO optimization
- Operations monitoring: Crashlytics crash collection + Performance network tracing + App Center distribution
2. A Story of Crashing on Launch Day
(1) The Pain: Works in Development, 5% Crash Rate in Production
Bob spent 4 months developing ShopApp. On launch day, the crash rate was 5%. Causes: Android R8 obfuscation stripped Firestore serialization class names (deserialization failed); iOS was rejected for missing camera permission description; the Web version homepage took 8 seconds to load (no code splitting). Emergency fixes + re-review took another 2 weeks.
(2) Build Optimization + Pre-release Checklist Solution
Before launch, execute build optimizations (obfuscation rules, code splitting, asset compression) + a release checklist (permissions, signing, ProGuard rules, TestFlight pre-review) to ensure first-launch quality.
(3) The Result: First Launch Crash Rate < 0.1%
After using the checklist on his second project, Bob achieved a first-launch crash rate of 0.08%, passed review on the first submission, and had a Web first-contentful paint of 1.5 seconds.
3. Build Optimization
(1) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Android ProGuard / R8 rules
# flutter_proguard_rules.pro
# Keep Firestore model classes (used by json_serializable)
-keepclassmembers class com.shopapp..model. {
<fields>;
}
# Keep freezed generated classes
-keep class com.shopapp...freezed.dart { *; }
# Keep Firebase classes
-keep class io.flutter.plugins.firebase.** { *; }
-keep class com.google.firebase.** { *; }
# Keep Stripe SDK
-keep class com.stripe.android.** { *; }
# Keep Google Sign-In
-keep class com.google.android.gms.auth.** { *; }
# Remove logging in release
-assumenosideeffects class android.util.Log {
public static *** d(...);
public static *** v(...);
public static *** i(...);
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(2) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Flutter build configuration
# pubspec.yaml build optimization
flutter:
uses-material-design: true
# Exclude unused locales
generate: true
# android/app/build.gradle
android {
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
// Split per ABI to reduce APK size
splits {
abi {
enable true
reset()
include 'armeabi-v7a', 'arm64-v8a', 'x86_64'
universalApk false
}
}
}
(3) Build Optimization Comparison
| Optimization | Before | After | Savings |
|---|---|---|---|
| APK size (arm64) | 28 MB | 12 MB | 57% |
| Web first-contentful paint | 8.2 s | 1.5 s | 82% |
| Dart code size | 6.4 MB | 2.1 MB | 67% |
| Startup time (cold) | 3.5 s | 1.8 s | 49% |
4. Android Deployment
(1) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Signing key configuration
# Generate signing keystore
keytool -genkey -v -keystore shopapp-release.jks -keyalg RSA -keysize 2048 -validity 10000 -alias shopapp
# Create key.properties
cat > android/key.properties << 'EOF'
storePassword=STORE_PASSWORD
keyPassword=KEY_PASSWORD
keyAlias=shopapp
storeFile=../shopapp-release.jks
EOF
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(2) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: build.gradle signing integration
// android/app/build.gradle
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(3) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Build App Bundle and upload
# Build App Bundle (recommended over APK for Play Store)
flutter build appbundle --release --obfuscate --split-debug-info=build/debug-info
# Upload to Google Play Console
# Option 1: Manual via Play Console UI
# Option 2: Fastlane
cd android && fastlane supply --aab ../build/app/outputs/bundle/release/app-release.aab --track internal
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(4) Android Release Checklist
| # | Check Item | Status |
|---|---|---|
| 1 | Signing key generated and backed up | ☐ |
| 2 | key.properties is not in version control | ☐ |
| 3 | ProGuard rules cover all third-party SDKs | ☐ |
| 4 | versionCode / versionName updated | ☐ |
| 5 | Permission declarations minimized | ☐ |
| 6 | App Bundle (not APK) for upload | ☐ |
| 7 | Store screenshots + description prepared | ☐ |
| 8 | Privacy Policy URL configured | ☐ |
5. iOS Deployment
(1) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Info.plist permission configuration
<!-- ios/Runner/Info.plist -->
`<key>`NSCameraUsageDescription</key>
`<string>`ShopApp needs camera access to scan product barcodes.</string>
`<key>`NSPhotoLibraryUsageDescription</key>
`<string>`ShopApp needs photo access to upload product reviews.</string>
`<key>`NSLocationWhenInUseUsageDescription</key>
`<string>`ShopApp uses location for local delivery estimates.</string>
`<key>`CFBundleURLTypes</key>
`<array>`
`<dict>`
`<key>`CFBundleURLSchemes</key>
`<array>`
`<string>`com.googleusercontent.apps.YOUR_CLIENT_ID</string>
</array>
`</dict>`
</array>
(2) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Fastlane iOS release
# ios/fastlane/Fastfile
default_platform(:ios)
platform :ios do
desc "Build and upload to TestFlight"
lane :beta do
build_app(
workspace: "Runner.xcworkspace",
scheme: "Runner",
export_method: "app-store",
include_bitcode: false,
export_options: {
compileBitcode: false,
provisioningProfiles: {
"com.shopapp.app" => "match AppStore com.shopapp.app"
}
}
)
upload_to_testflight(
skip_waiting_for_build_processing: true
)
end
desc "Submit to App Store review"
lane :release do
beta
deliver(
submit_for_review: true,
automatic_release: true,
force: true,
metadata_path: "./metadata"
)
end
end
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(3) Common iOS Review Rejection Reasons
| Rejection Reason | Solution |
|---|---|
| Missing permission descriptions | Add NS*UsageDescription to Info.plist |
| Payment not using IAP (virtual goods) | Use StoreKit for virtual goods, Stripe for physical |
| Login forces social account binding | Provide email/password login option |
| WebView wrapper app | Ensure native functionality > 50% |
| Incomplete metadata | Fill in age rating, privacy policy URL |
6. Web Deployment
(1) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Firebase Hosting configuration
// firebase.json
{
"hosting": {
"public": "build/web",
"ignore": ["firebase.json", "/.*", "/node_modules/**"],
"rewrites": [
{ "source": "**", "destination": "/index.html" }
],
"headers": [
{
"source": "**/*.@(js|css|wasm)",
"headers": [
{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
]
},
{
"source": "**/*.@(jpg|jpeg|gif|png|svg|webp|ico)",
"headers": [
{ "key": "Cache-Control", "value": "public, max-age=604800" }
]
},
{
"source": "/index.html",
"headers": [
{ "key": "Cache-Control", "value": "no-cache" }
]
}
]
}
}
(2) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Web build and deploy
# Build web with CanvasKit renderer (better performance)
flutter build web --release --web-renderer canvaskit --pwa-strategy offline_first
# Deploy to Firebase Hosting
firebase deploy --only hosting
# Or deploy to custom server with Nginx
scp -r build/web/* user@server:/var/www/shopapp/
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(3) Web Performance Optimization Comparison
| Optimization Strategy | First Paint | LCP | FID |
|---|---|---|---|
| Unoptimized (HTML renderer) | 8.2 s | 7.8 s | 180 ms |
| CanvasKit renderer | 3.1 s | 2.8 s | 45 ms |
| + Code split + lazy | 1.5 s | 1.2 s | 30 ms |
| + PWA + Service Worker | 0.8 s (repeat) | 0.5 s | 15 ms |
7. Operations Monitoring
(1) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Crashlytics integration
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'dart:ui' show PlatformDispatcher;
// Dependencies: firebase_core: ^2.0.0, firebase_crashlytics: ^3.0.0, firebase_auth: ^4.0.0
// DefaultFirebaseOptions / ShopApp come from the ShopApp project
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
// Crashlytics
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true;
};
// Pass all uncaught errors to Crashlytics
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
// Set user identifier for crash reports
FirebaseAuth.instance.authStateChanges().listen((user) {
if (user != null) {
FirebaseCrashlytics.instance.setUserIdentifier(user.uid);
}
});
// Custom keys for context
FirebaseCrashlytics.instance.setCustomKey('app_version', '1.0.0');
FirebaseCrashlytics.instance.setCustomKey('environment', 'production');
runApp(const ShopApp());
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
(2) ▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
: Performance Monitoring
import 'package:dio/dio.dart';
import 'package:firebase_performance/firebase_performance.dart';
// Dependencies: firebase_performance: ^0.9.0, dio: ^5.0.0 (add to dependencies)
class ShopPerformance {
static final _perf = FirebasePerformance.instance;
static Future<void> trackProductLoad(String productId) async {
final trace = _perf.newTrace('product_load');
trace.putAttribute('product_id', productId);
await trace.start();
try {
// ... load product ...
} finally {
await trace.stop();
}
}
static Future<void> trackSearch(String query, int results) async {
final trace = _perf.newTrace('search');
trace.putAttribute('query', query);
trace.putMetric('results_count', results);
await trace.start();
await trace.stop();
}
static Future<void> trackCheckout(double total) async {
final trace = _perf.newTrace('checkout');
trace.putMetric('order_total_cents', (total * 100).toInt());
await trace.start();
await trace.stop();
}
}
// HTTP performance auto-tracking with Dio
class PerformanceInterceptor extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
options.extra['trace'] = FirebasePerformance.instance.newHttpMetric(
options.uri.toString(), HttpMethod.Post);
(options.extra['trace'] as HttpMetric).start();
handler.next(options);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
final trace = response.requestOptions.extra['trace'] as HttpMetric?;
trace?.httpResponseCode = response.statusCode;
trace?.stop();
handler.next(response);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
final trace = err.requestOptions.extra['trace'] as HttpMetric?;
trace?.httpResponseCode = err.response?.statusCode;
trace?.stop();
handler.next(err);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
8. Complete Example: Pre-release Automated Check Script
// tool/release_check.dart
import 'dart:io';
// Pure Dart script, no Flutter dependency, run with dart run tool/release_check.dart
enum Platform { android, ios, web }
class ReleaseChecker {
static Future<bool> run(Platform platform) async {
final results = <String, bool>{};
results['version_updated'] = _checkVersionUpdated();
results['changelog_updated'] = _checkChangelog();
results['no_debug_print'] = _checkNoDebugPrint();
results['proguard_rules'] = platform == Platform.android ? _checkProguard() : true;
results['info_plist'] = platform == Platform.ios ? _checkInfoPlist() : true;
results['privacy_policy'] = _checkPrivacyPolicy();
results['signing_config'] = _checkSigningConfig(platform);
results['test_pass'] = await _runTests();
results['analyze_pass'] = await _runAnalyze();
final allPass = results.values.every((v) => v);
if (!allPass) {
print('Release check FAILED:');
results.forEach((k, v) { if (!v) print(' ✗ $k'); });
} else {
print('All release checks PASSED!');
}
return allPass;
}
static bool _checkVersionUpdated() {
// Compare current pubspec.yaml version with last git tag
return true; // Simplified
}
static bool _checkChangelog() => File('CHANGELOG.md').existsSync();
static bool _checkNoDebugPrint() {
// Grep for debugPrint / print() in lib/
return true; // Simplified
}
static bool _checkProguard() => File('android/app/proguard-rules.pro').existsSync();
static bool _checkInfoPlist() {
final plist = File('ios/Runner/Info.plist').readAsStringSync();
return plist.contains('NSCameraUsageDescription') && plist.contains('NSPhotoLibraryUsageDescription');
}
static bool _checkPrivacyPolicy() => true;
static bool _checkSigningConfig(Platform platform) {
if (platform == Platform.android) return File('android/key.properties').existsSync();
return true; // iOS uses Xcode managed signing
}
static Future<bool> _runTests() async {
final result = await Process.run('flutter', ['test']);
return result.exitCode == 0;
}
static Future<bool> _runAnalyze() async {
final result = await Process.run('flutter', ['analyze']);
return result.exitCode == 0;
}
}
void main(List<String> args) async {
final platform = switch (args.firstOrNull) {
'android' => Platform.android,
'ios' => Platform.ios,
'web' => Platform.web,
_ => Platform.android,
};
final pass = await ReleaseChecker.run(platform);
exit(pass ? 0 : 1);
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slight by platform.
9. Deployment Process Overview
graph TD
CODE[Source Code] --> ANALYZE[flutter analyze]
ANALYZE --> TEST[flutter test]
TEST --> CHECK{Release Check}
CHECK -->|FAIL| FIX[Fix Issues]
FIX --> ANALYZE
CHECK -->|PASS| BUILD[flutter build]
BUILD --> ANDROID[Android: AAB → Play Console]
BUILD --> IOS[iOS: IPA → TestFlight → App Store]
BUILD --> WEB[Web: Firebase Hosting]
ANDROID --> MONITOR[Crashlytics + Performance]
IOS --> MONITOR
WEB --> MONITOR
MONITOR --> ITERATE[Iterate & Release Next Version]
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed; please use `flutter run` on your local machine for comparison. Actual UI/state may vary slightly by platform.
❓ FAQ
📖 Summary
- Build optimization: R8 obfuscation + ABI splitting + CanvasKit renderer — APK reduced by 57%, Web first paint reduced by 82%
- Android: signing key → App Bundle → Play Console → internal/beta/production rollout
- iOS: Info.plist permissions → Fastlane → TestFlight → App Store review
- Web: Firebase Hosting + PWA + Service Worker + CDN cache strategy
- Operations: Crashlytics crash collection + Performance network tracing + automated release checks
📝 Exercises
- Basic (Difficulty ⭐): Configure Android signing key + ProGuard rules, build a Release App Bundle, and verify the size optimization.
- Intermediate (Difficulty ⭐⭐): Configure Crashlytics + Performance Monitoring, simulate a crash and a slow request, and verify monitoring data reporting.
- Challenge (Difficulty ⭐⭐⭐): Write a complete CI/CD pipeline (GitHub Actions): analyze → test → release check → build (android + ios + web) → deploy, achieving one-click multi-platform release.