본문으로 건너뛰기
cccskills
무료GitHub에 공개

flutter-pageview-url-routing-reorder-loop

Fix infinite rebuild loop in Flutter when using PageView with URL-based routing (GoRouter) and reactive state management (Riverpod/BLoC). Use when: (1) RAPID REBUILD warnings appear in console (#20+), (2) "setState() or markNeedsBuild() called during build" errors from ValueListenableBuilder, (3) Video feed or list-based PageView is frozen and won't swipe, (4) Overlay or UI elements flicker between visible/invisible rapidly, (5) Logs show item "moved from index X to Y" repeatedly. Caused by tracking items by ID and updating URL when reactive list reorders.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md6.3 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Flutter PageView + URL Routing Reorder Detection Loop

Problem

When a PageView is synced bidirectionally with URL-based routing (e.g., GoRouter /home/:index) and the data source is a reactive provider (Riverpod, BLoC stream), attempting to track the currently-viewed item by its ID and update the URL when the item moves to a different index in the list creates an infinite feedback loop.

Context / Trigger Conditions

Symptoms:

  • Console shows RAPID REBUILD #42! warnings (build count growing rapidly)
  • setState() or markNeedsBuild() called during build errors from ValueListenableBuilder
  • PageView is frozen - user swipes but page bounces back to same position
  • UI overlay (social buttons, controls) flickers between visible and invisible
  • Logs show repeated pattern: Video X moved from index 4 -> 3, updating URL

Architecture that triggers this:

  • PageView.builder with onPageChanged updating URL via context.go('/feed/$index')
  • URL-derived index synced back to PageController via jumpToPage() during build
  • Reactive data source (Riverpod provider, stream) that can re-emit with reordered items
  • Item tracking: _currentItemId compared against list to detect "moves"

Example of the anti-pattern:

// IN BUILD METHOD - creates feedback loop!
if (_currentVideoStableId != null && videos.isNotEmpty) {
  final currentVideoIndex = videos.indexWhere(
    (v) => v.stableId == _currentVideoStableId,
  );
  if (currentVideoIndex != -1 && currentVideoIndex != urlIndex) {
    // This triggers URL update -> rebuild -> PageController sync ->
    // onPageChanged -> URL update -> INFINITE LOOP
    context.go('/home/$currentVideoIndex');
  }
}

Solution

Remove item-tracking reorder detection entirely. The PageController should be the sole source of truth for which page the user is viewing.

Step 1: Remove tracking state

// REMOVE these fields:
// String? _currentVideoStableId;
// bool _urlUpdateScheduled = false;

Step 2: Remove reorder detection block

Remove any code in build() that:

  • Searches for a tracked item ID in the current list
  • Compares found index against URL index
  • Schedules URL updates when indices differ

Step 3: Keep only one-way sync patterns

User swipe -> URL (one-way):

onPageChanged: (newIndex) {
  if (newIndex != urlIndex) {
    context.go('/home/$newIndex');
  }
}

External navigation -> PageController (one-way):

if (urlIndex != _lastUrlIndex) {
  _lastUrlIndex = urlIndex;
  controller.jumpToPage(urlIndex);
}

These two paths don't create loops because:

  • User swipe: URL updates, next build sees matching urlIndex -> no sync needed
  • External nav: URL changes, sync fires, onPageChanged fires but newIndex == urlIndex -> no URL update

The Feedback Loop Explained

┌─ Reactive provider re-emits (new data from server) ─┐
│                                                       │
▼                                                       │
Build runs with new video list                          │
│                                                       │
▼                                                       │
Reorder detection: "Video X moved from idx 4 to 3"     │
│                                                       │
▼                                                       │
Schedule URL update: context.go('/home/3')              │
│                                                       │
▼                                                       │
Build runs: urlIndex=3, PageController at page 4        │
│                                                       │
▼                                                       │
Sync: jumpToPage(3)                                     │
│                                                       │
▼                                                       │
onPageChanged(3) fires → context.go('/home/3')          │
│                                                       │
▼                                                       │
But PageController was at 4, which showed different     │
video → _currentVideoStableId mismatches → detects      │
"move" again → URL update to /home/4                    │
│                                                       │
└───────── INFINITE LOOP ──────────────────────────────┘

Verification

After removing reorder detection:

  1. No more RAPID REBUILD warnings in console
  2. No setState() called during build errors
  3. Swiping between pages works smoothly
  4. UI overlays stay visible on the active page
  5. No "moved from index X to Y" log spam

Notes

  • Why reorder detection seems needed: When a reactive list reorders (e.g., new items prepended), the user's current page index points to a different item. However, trying to "follow" the item creates worse UX (infinite loop) than staying on the same page index.

  • Alternative if position preservation is critical: Instead of URL-based reorder detection, stabilize the list order. Either:

    • Don't reorder while the user is actively viewing (batch updates)
    • Use a stable sort that preserves relative positions of existing items
    • Only prepend/append new items, never reorder existing ones
  • Related pattern: flutter-pageview-implicit-scrolling-snapback addresses a different PageView issue (snap-back on state rebuild) but can co-occur with this loop.

  • Framework-agnostic: While this was discovered with GoRouter + Riverpod, the same pattern applies to any PageView + URL routing + reactive state combination (Navigator 2.0, auto_route, BLoC streams, etc.)

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 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-mobile2652026년 10월 21일 업데이트

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-mobile2652026년 10월 21일 업데이트

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-mobile2652026년 10월 21일 업데이트

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-mobile2652026년 10월 21일 업데이트

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-mobile2652026년 10월 21일 업데이트

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-mobile2652026년 10월 21일 업데이트

divinevideo의 스킬 모두 보기

이 스킬의 문제 신고