本文へ移動
cccskills
無料GitHub で公開

flutter-startup-network-blocking

Fix slow Flutter app startup caused by blocking network operations during initialization. Use when: (1) App takes several seconds to show first frame, (2) Startup logs show sequential network operations (WebSocket connections, API calls), (3) Services initialize during startup that aren't needed until user authenticates. Covers: converting sequential network ops to parallel with Future.wait(), deferring service initialization until actually needed (lazy init), and identifying blocking operations in Riverpod/provider initialization chains.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md4.8 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Flutter Startup Network Blocking

Problem

Flutter app startup is slow because network operations (WebSocket connections, API calls, service initialization) run sequentially during the initialization phase, blocking the first frame from rendering. With multiple relay/server connections, worst-case startup time becomes O(n × timeout) instead of O(max timeout).

Context / Trigger Conditions

  • App takes 3+ seconds to show first frame on fresh launch
  • Startup logs show sequential "connecting to relay X... connecting to relay Y..."
  • Services that require authentication initialize even for unauthenticated users
  • _initializeCoreServices() or similar contains multiple awaited network operations
  • Riverpod providers eagerly initialize network-dependent services in their build() method

Solution

1. Identify Blocking Operations

Look for sequential awaits in startup code:

// BAD: Sequential - each connection blocks the next
for (final url in relays) {
  await connectToRelay(url);  // Blocks startup!
}

2. Convert Sequential to Parallel

Use Future.wait() to run all connections simultaneously:

// GOOD: Parallel - all connections run at once
final results = await Future.wait(
  relays.map((url) async {
    final success = await connectToRelay(url);
    return MapEntry(url, success);
  }),
);

3. Defer Non-Critical Service Initialization

Move network-dependent services out of the critical startup path:

Before (blocking startup):

Future<void> _initializeCoreServices(ProviderContainer container) async {
  await container.read(authServiceProvider).initialize();
  await container.read(nostrServiceProvider).initialize();  // BLOCKS for relay connections!
  await container.read(otherServiceProvider).initialize();
}

After (lazy initialization):

Future<void> _initializeCoreServices(ProviderContainer container) async {
  // NOTE: NostrService initializes lazily when user authenticates
  await container.read(authServiceProvider).initialize();
  await container.read(seenVideosServiceProvider).initialize();
  // NostrService NOT initialized here - happens when auth state changes
}

4. Use Provider Dependencies for Lazy Init

Let Riverpod handle lazy initialization through provider dependencies:

@riverpod
NostrClient nostrClient(NostrClientRef ref) {
  final authService = ref.watch(authServiceProvider);

  // Only creates client when auth state is ready
  if (!authService.isAuthenticated) {
    return NostrClient.disconnected();
  }

  // Initialize lazily when actually needed
  final client = NostrClient(relays: authService.userRelays);
  Future.microtask(() => client.initialize());
  return client;
}

Verification

  1. Check startup logs for "First frame rendered in Xms" - should be < 2000ms
  2. Verify network operations happen AFTER first frame timestamp in logs
  3. For unauthenticated users, relay connections should NOT appear in startup logs

Example

Startup improvement achieved:

  • Before: First frame at 3500ms+ (waiting for 5 relays × ~700ms each)
  • After: First frame at 1426ms (parallel connections happen post-frame)

Log pattern showing fix working:

[18:15:17.538] First frame rendered in 1426ms
[18:15:17.556] Creating NostrClient...  // AFTER first frame!

Notes

  • This pattern applies to any async initialization, not just WebSockets
  • Consider timeout handling when parallelizing - use Future.wait with error handling
  • For critical services, use a loading screen rather than blocking the main thread
  • Profile with Flutter DevTools Timeline to identify other startup bottlenecks
  • Remember that Future.wait() fails fast by default - use try/catch inside the map if you want partial success

Related Patterns

  • Splash screen with async initialization
  • Riverpod AsyncNotifier for lazy-loaded state
  • Background service initialization after first frame

References

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y". Use when: (1) ExternalSecret shows OutOfSync in ArgoCD but won't sync, (2) ArgoCD application status shows "namespace X is not permitted in project 'infrastructure'", (3) ExternalSecret targets a namespace managed by a different ArgoCD project, (4) Using apps-of-apps pattern with separate infrastructure and application projects.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language. After selection, generates AI image prompts and visual briefs section-by-section. Use when the user shares content and needs visual direction, image sourcing, or creative direction for any material.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Fix "Null check operator used on a null value" errors when an object is set to null during an async await. Use when: (1) Object reference is nullified while awaiting, (2) Code accesses object with ! after await returns, (3) Cancel/dispose operations run concurrently with async operations on same object. Solution: capture local reference before await.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Add custom metadata headers (x-amz-meta-*) to AWS v4 signed requests for GCS S3-compatible API. Use when: (1) Adding custom metadata to GCS uploads via S3 API, (2) Getting signature mismatch errors after adding new headers, (3) x-amz-meta-* headers being ignored or causing 403 errors. Custom headers MUST be included in canonical headers and signed headers list.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings. Use when: (1) Password authentication fails with correct password, (2) Secret created with `<<< "value"` syntax, (3) Error like "password authentication failed" or "invalid token" despite correct value. Bash here-strings (`<<<`) add a trailing newline that corrupts secrets.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp). Use when: (1) Media moderation, transcoding, or analysis silently skips files from Blossom or content-addressed storage servers, (2) URL extraction from Nostr event tags (imeta, r tags) drops URLs without recognized extensions, (3) CDN fallback URLs append .mp4 but the actual server uses extensionless content-addressed paths like /{sha256}. Common in Nostr video events (kind 34236) where different clients use different URL formats.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月10日 更新

divinevideo のスキルをすべて見る

このスキルの問題を報告する