# Flutter/Dart: Async Work Blocking UI Spinner

## Pattern: Spinner hangs because async work runs in critical path

**Symptom**: `CircularProgressIndicator` or button loading spinner never stops on Android/iOS.

**Root cause**: `await` on async operation (network, permissions, platform channels) inside the same `try` block that controls `_isLoading = false`.

```dart
// ❌ BAD: Notification scheduling blocks spinner
Future<void> _save() async {
  setState(() => _isSaving = true);
  try {
    await saveWeight(weight);
    await notificationService.schedule(...);  // ← blocks here
    Navigator.pop();
  } catch (e) {
    setState(() => _isSaving = false);  // never reached if above hangs
  }
}
```

## Fix: Fire-and-forget background work

```dart
// ✓ GOOD: Critical path returns immediately
Future<void> _save() async {
  setState(() => _isSaving = true);
  try {
    await saveWeight(weight);
    if (mounted) {
      Navigator.pop();
      setState(() => _isSaving = false);
    }
    // Fire-and-forget: notification failure must not block user
    Future.microtask(() => _scheduleReminderInBackground());
  } catch (e) {
    if (mounted) setState(() => _isSaving = false);
  }
}

void _scheduleReminderInBackground() async {
  try {
    final service = await ref.read(notificationServiceProvider.future);
    await service.schedule(...);
  } catch (e, st) {
    logError('Background reminder failed', error: e, st: st);
  }
}
```

## Android-Specific Triggers

| Trigger | Why it blocks | Mitigation |
|---------|---------------|------------|
| `flutter_timezone` first call | JNI + tz database load | Eager init at app start |
| `timezone` package init | Location lookup | Pre-warm in `main()` |
| `AndroidScheduleMode.inexactAllowWhileIdle` | Doze mode defers | Use `exact` for critical reminders |
| Permission dialog (`requestPermissions`) | Modal system dialog | Request earlier, not in save path |
| Platform channel (MethodChannel) | Main thread serialization | Keep calls minimal, batch if possible |

## Investigation Checklist for Spinner Hangs

1. Find the `setState(() => _isLoading = true)`
2. Trace every `await` between that and `setState(() => _isLoading = false)`
3. Identify which `await` can hang indefinitely (permissions, network, platform)
4. Move non-critical awaits to `Future.microtask` / unawaited future
5. Ensure `mounted` checks before any `setState` after async gap

## Related Files in BiteBudget

- `lib/features/bodydata/ui/widgets/weight_update_bottom_sheet.dart` — `_save()` method
- `lib/core/provider/notification_provider.dart` — `NotificationService.schedule()`
- `lib/features/bodydata/service/body_save_service.dart` — actual weight save (fast)
