onInit method

  1. @override
void onInit()
override

Called immediately after the widget is allocated in memory. You might use this to initialize something for the controller.

Implementation

@override
void onInit() {
  Log.debug('onInit()', '$runtimeType');

  for (var e in source.values) {
    final bool initial = e.id == key.value;
    posts.add(
      Post.fromMediaItem(e, initial: initial ? initialIndex : 0)..init(),
    );
  }
  posts.sort();

  index = RxInt(max(0, posts.indexWhere((e) => e.id == key.value)));

  vertical = PageController(
    initialPage: _index,
    keepPage: false,
    viewportFraction: 1.05,
  );

  _currentPageIndex = _index;

  _sourceSubscription?.cancel();
  _sourceSubscription = source.items.changes.listen((e) {
    switch (e.op) {
      case OperationKind.added:
      case OperationKind.updated:
        final MediaItem? item = e.value;

        if (item != null) {
          final Post? existing = posts.firstWhereOrNull((p) => p.id == e.key);
          if (existing == null) {
            final bool initial = item.id == key.value;
            final Post post = Post.fromMediaItem(
              item,
              initial: initial ? initialIndex : 0,
            );

            posts.add(post..init());
            posts.sort();
          } else {
            // TODO: Update the item.
            // existing.description = item.d;
          }
        }
        break;

      case OperationKind.removed:
        posts.removeWhere((p) {
          final bool test = p.id == e.key;
          if (test) {
            p.dispose();
          }

          return test;
        });
        break;
    }

    index.value = max(0, posts.indexWhere((e) => e.id == key.value));
    if (vertical.hasClients && (vertical.page ?? 0) != index.value) {
      _ignorePageListener = true;
      vertical.jumpToPage(index.value);
      _ignorePageListener = false;
    }

    hasPreviousPage.value = index.value > 0;
    hasNextPage.value = index.value < posts.length - 1;
  });

  _volumeDebounce = debounce(_volume, (value) async {
    await _settingsRepository.setVideoVolume(value);
  }, time: Duration(milliseconds: 200));

  _initResource();

  HardwareKeyboard.instance.addHandler(_keyboardHandler);
  BackButtonInterceptor.add(_backHandler);
  vertical.addListener(_pageListener);
  super.onInit();
}