build method

  1. @override
Widget build(
  1. BuildContext context
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  // تحديث رابط أيقونة التطبيق إذا وُجد
  if (appIconUrlForPlayAudioInBackground != null &&
      appIconUrlForPlayAudioInBackground!.isNotEmpty) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      AudioCtrl.instance
          .updateAppIconUrl(appIconUrlForPlayAudioInBackground!);
    });
  }

  // إعداد وضع التحديد المتعدد والتظليل الخارجي (بدون Stateful)
  WidgetsBinding.instance.addPostFrameCallback((_) {
    final ctrl = QuranCtrl.instance;
    ctrl.setMultiSelectMode(enableMultiSelect);
    final combined = <int>{};
    if (highlightedAyahs.isNotEmpty) {
      combined.addAll(highlightedAyahs);
    }
    if (highlightedAyahNumbersBySurah.isNotEmpty) {
      highlightedAyahNumbersBySurah.forEach((surah, ayahs) {
        for (final n in ayahs) {
          final id = ctrl.getAyahUQBySurahAndAyah(surah, n);
          if (id != null) combined.add(id);
        }
      });
    }
    if (highlightedAyahNumbersInPages.isNotEmpty) {
      for (final item in highlightedAyahNumbersInPages) {
        combined.addAll(ctrl.getAyahUQsForPagesByAyahNumbers(
            startPage: item.start,
            endPage: item.end,
            ayahNumbers: item.ayahs));
      }
    }
    if (highlightedRanges.isNotEmpty) {
      for (final r in highlightedRanges) {
        combined.addAll(ctrl.getAyahUQsForSurahAyahRange(
          startSurah: r.startSurah,
          startAyah: r.startAyah,
          endSurah: r.endSurah,
          endAyah: r.endAyah,
        ));
      }
    }
    if (highlightedRangesText.isNotEmpty) {
      for (final s in highlightedRangesText) {
        final parsed = ctrl.parseSurahAyahRangeString(s);
        if (parsed != null) {
          combined.addAll(ctrl.getAyahUQsForSurahAyahRange(
            startSurah: parsed.$1,
            startAyah: parsed.$2,
            endSurah: parsed.$3,
            endAyah: parsed.$4,
          ));
        }
      }
    }
    if (combined.isNotEmpty) {
      ctrl.setExternalHighlights(combined.toList());
    }
  });

  final (sp, ep) = _resolveRange();
  final int startIndex = sp - 1; // محول إلى 0-based
  final int count = (ep - sp) + 1; // عدد الصفحات

  if (QuranCtrl.instance.isDownloadFonts) {
    // تنفيذ بعد انتهاء الإطار لتجنّب أي تجميد
    Future.microtask(() => QuranCtrl.instance
        .prepareFonts(startIndex, isFontsLocal: isFontsLocal!));
  }
  return ScreenUtilInit(
    designSize: const Size(392.72727272727275, 800.7272727272727),
    minTextAdapt: true,
    splitScreenMode: true,
    builder: (_, __) => GetBuilder<QuranCtrl>(
      builder: (quranCtrl) {
        Widget singlePage(int globalIndex) {
          return InkWell(
            onTap: () {
              if (onPagePress != null) {
                onPagePress!();
              } else {
                quranCtrl.showControlToggle();
                if (!enableMultiSelect) {
                  quranCtrl.clearSelection();
                }
                quranCtrl.state.overlayEntry?.remove();
                quranCtrl.state.overlayEntry = null;
              }
            },
            focusColor: Colors.transparent,
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            child: RepaintBoundary(
              key: ValueKey('quran_partial_page_$globalIndex'),
              child: PageViewBuild(
                circularProgressWidget: circularProgressWidget,
                languageCode: languageCode,
                juzName: juzName,
                sajdaName: sajdaName,
                topTitleChild: topTitleChild,
                bookmarkList: bookmarkList,
                ayahSelectedFontColor: ayahSelectedFontColor,
                textColor: textColor,
                ayahIconColor: ayahIconColor,
                showAyahBookmarkedIcon: showAyahBookmarkedIcon,
                onAyahLongPress: onAyahLongPress,
                bookmarksColor: bookmarksColor,
                surahInfoStyle: surahInfoStyle,
                surahNameStyle: surahNameStyle,
                bannerStyle: bannerStyle,
                basmalaStyle: basmalaStyle,
                onSurahBannerPress: onSurahBannerPress,
                surahNumber: surahNumber,
                ayahSelectedBackgroundColor: ayahSelectedBackgroundColor,
                onPagePress: onPagePress,
                isDark: isDark,
                fontsName: fontsName,
                ayahBookmarked: ayahBookmarked,
                anotherMenuChild: anotherMenuChild,
                anotherMenuChildOnTap: anotherMenuChildOnTap,
                secondMenuChild: secondMenuChild,
                secondMenuChildOnTap: secondMenuChildOnTap,
                userContext: parentContext,
                pageIndex: globalIndex,
                quranCtrl: quranCtrl,
                isFontsLocal: isFontsLocal!,
              ),
            ),
          );
        }

        Widget body;
        if (withPageView) {
          // PageView محلي على النطاق فقط
          final controller = PageController(initialPage: 0);
          body = NotificationListener<ScrollEndNotification>(
            onNotification: (notification) {
              final metrics = notification.metrics;
              if (metrics is PageMetrics) {
                final int currentLocal = (metrics.page ??
                        (metrics.pixels / metrics.viewportDimension))
                    .round();
                final int currentGlobal = startIndex + currentLocal;
                if (quranCtrl.isDownloadFonts) {
                  Future.microtask(() => quranCtrl.prepareFonts(
                        currentGlobal,
                        isFontsLocal: isFontsLocal!,
                      ));
                }
              }
              return false;
            },
            child: PageView.builder(
              itemCount: count,
              controller: controller,
              padEnds: false,
              physics: const ClampingScrollPhysics(),
              allowImplicitScrolling: false,
              clipBehavior: Clip.hardEdge,
              onPageChanged: (localIndex) {
                final globalIndex = startIndex + localIndex;
                WidgetsBinding.instance.addPostFrameCallback((_) async {
                  if (onPageChanged != null) {
                    onPageChanged!(globalIndex);
                  } else {
                    quranCtrl.state.overlayEntry?.remove();
                    quranCtrl.state.overlayEntry = null;
                  }
                  quranCtrl.state.currentPageNumber.value = globalIndex + 1;
                  quranCtrl.saveLastPage(globalIndex + 1);
                });
                if (quranCtrl.isDownloadFonts) {
                  // تنفيذ بعد انتهاء الإطار لتجنّب أي تجميد
                  Future.microtask(() => quranCtrl.prepareFonts(startIndex,
                      isFontsLocal: isFontsLocal!));
                }
              },
              itemBuilder: (ctx, localIndex) {
                final globalIndex = startIndex + localIndex;
                return singlePage(globalIndex);
              },
            ),
          );
        } else {
          if (count == 1) {
            body = singlePage(startIndex);
          } else {
            // عرض رأسي لعدة صفحات (استخدمه بحذر للنطاقات الكبيرة)
            body = ListView.builder(
              padding: EdgeInsets.zero,
              itemCount: count,
              itemBuilder: (_, localIndex) {
                final globalIndex = startIndex + localIndex;
                return singlePage(globalIndex);
              },
            );
          }
        }

        return Directionality(
          textDirection: TextDirection.rtl,
          child: Scaffold(
            backgroundColor:
                backgroundColor ?? AppColors.getBackgroundColor(isDark),
            body: SafeArea(
              child: Stack(
                alignment: Alignment.center,
                children: [
                  body,
                  // تم تفعيل وضع التحديد المتعدد في initState ويُعاد ضبطه في dispose
                  GetBuilder<QuranCtrl>(
                    id: 'isShowControl',
                    builder: (quranCtrl) => Stack(
                      alignment: Alignment.center,
                      children: [
                        isShowAudioSlider!
                            ? BottomSlider(
                                isVisible:
                                    QuranCtrl.instance.isShowControl.value,
                                onClose: () {
                                  QuranCtrl.instance.isShowControl.value =
                                      false;
                                  SliderController.instance
                                      .hideBottomContent();
                                },
                                isDark: isDark,
                                sliderHeight: UiHelper.currentOrientation(
                                    0.0, 40.0, context),
                                style: ayahStyle ?? AyahAudioStyle(),
                                contentChild: const SizedBox.shrink(),
                                child: Flexible(
                                  child: AyahsAudioWidget(
                                    style: ayahStyle ?? AyahAudioStyle(),
                                  ),
                                ),
                              )
                            : const SizedBox.shrink(),
                        appBar == null &&
                                useDefaultAppBar &&
                                quranCtrl.isShowControl.value
                            ? _QuranTopBar(
                                languageCode ?? 'ar',
                                isDark,
                                style: surahStyle ?? SurahAudioStyle(),
                                backgroundColor: backgroundColor,
                                downloadFontsDialogStyle:
                                    downloadFontsDialogStyle,
                                isFontsLocal: isFontsLocal,
                                topBarStyle: topBarStyle ??
                                    QuranTopBarStyle.defaults(isDark: isDark),
                              )
                            : const SizedBox.shrink(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    ),
  );
}