getPageController method

PreloadPageController getPageController(
  1. BuildContext context
)

Implementation

PreloadPageController getPageController(BuildContext context) {
  final Orientation orientation = MediaQuery.of(context).orientation;

  // احسب قيمة الـ viewportFraction الهدف بناءً على حجم/اتجاه الشاشة
  // viewportFraction 0.5 فقط في الوضع الافتراضي على شاشات الديسكتوب العريضة
  // Other display modes always use 1.0 to show a single page
  final bool isWideDesktop =
      Responsive.isDesktop(context) && orientation == Orientation.landscape;
  final currentMode = state.displayMode.value;
  final bool useDualFraction =
      isWideDesktop && currentMode == QuranDisplayMode.defaultMode;
  double targetFraction = useDualFraction ? 0.5 : 1.0;

  log(
      'getPageController: isDesktop=${GetPlatform.isDesktop}, isWideDesktop=$isWideDesktop, '
      'targetFraction=$targetFraction',
      name: 'QuranCtrl');

  // أعد إنشاء المتحكم فقط عند تغيّر viewportFraction.
  // لا نتحقق من hasClients لأن jumpToPage في onInit ينشئ controller بـ initialPage صحيح
  // وإعادة إنشائه قبل ربطه بالـ PageView يضيع تلك القيمة.
  final bool needsNewController =
      quranPagesController.viewportFraction != targetFraction;

  if (needsNewController) {
    // حافظ على الفهرس الحالي للصفحة
    int currentIndex;
    if (quranPagesController.hasClients) {
      final double? p = quranPagesController.page;
      currentIndex =
          (p != null) ? p.round() : state.currentPageNumber.value - 1;
    } else {
      // قراءة مباشرة من التخزين — المصدر الأوثق للصفحة المحفوظة
      final savedPage = _quranRepository.getLastPage() ?? 1;
      currentIndex = savedPage - 1;
    }
    currentIndex = currentIndex.clamp(0, 603);
    // في وضع الصفحتين: محاذاة الفهرس إلى رقم زوجي لعرض الزوج الصحيح
    if (targetFraction < 1.0) {
      currentIndex = currentIndex - (currentIndex % 2);
    }
    log('Creating new PageController with initialPage: $currentIndex',
        name: 'QuranCtrl');

    final oldController = quranPagesController;
    quranPagesController = PreloadPageController(
      initialPage: currentIndex,
      keepPage: kIsWeb || GetPlatform.isDesktop,
      viewportFraction: targetFraction,
    );

    // تخلّص من المتحكم القديم بعد الإطار لتجنّب تعارضات التثبيت
    if (oldController != quranPagesController) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        try {
          oldController.dispose();
        } catch (_) {
          // تجاهل أي أخطاء تصريف إن كان قد صُرّف سابقًا
        }
      });
    }
  }
  return quranPagesController;
}