跳到正文
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(原文)

安装前可以查看交给 AI 代理的指令内容。

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

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

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月19日 更新

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月19日 更新

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月19日 更新

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月19日 更新

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月19日 更新

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月19日 更新

查看 divinevideo 的全部技能

报告此技能的问题