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() {
  scrollController.addListener(_scrollListener);

  chats.value = RxList(
    _chatService.paginated.values
        .map((e) => ChatEntry(e, chats.sort))
        .toList(),
  );

  chats.sort();

  HardwareKeyboard.instance.addHandler(_escapeListener);
  if (PlatformUtils.isMobile && !PlatformUtils.isWeb) {
    BackButtonInterceptor.add(_onBack, ifNotYetIntercepted: true);
  }

  // Adds the recipient of the provided [chat] to the [_recipients] and starts
  // listening to its updates.
  Future<void> listenUpdates(ChatEntry chat) async {
    final UserId? userId =
        chat.chat.value.members
            .firstWhereOrNull((u) => u.user.id != me)
            ?.user
            .id;

    if (userId != null) {
      RxUser? rxUser =
          chat.members.values
              .toList()
              .firstWhereOrNull((u) => u.user.id != me)
              ?.user;
      rxUser ??= await getUser(userId);
      if (rxUser != null) {
        _userSubscriptions.remove(userId)?.cancel();
        _userSubscriptions[userId] = rxUser.updates.listen((_) {});
      }
    }
  }

  chats.where((c) => c.chat.value.isDialog).forEach(listenUpdates);
  _chatsSubscription = _chatService.paginated.changes.listen((event) {
    switch (event.op) {
      case OperationKind.added:
        final entry = ChatEntry(event.value!, chats.sort);
        chats.add(entry);
        chats.sort();

        if (event.value!.chat.value.isDialog) {
          listenUpdates(entry);
        }
        break;

      case OperationKind.removed:
        chats.removeWhere((e) {
          if (e.chat.value.id == event.key) {
            e.dispose();
            return true;
          }

          return false;
        });

        if (event.value!.chat.value.isDialog) {
          final UserId? userId =
              event.value!.chat.value.members
                  .firstWhereOrNull((u) => u.user.id != me)
                  ?.user
                  .id;

          _userSubscriptions.remove(userId)?.cancel();
        }

        _scrollListener();
        break;

      case OperationKind.updated:
        chats.sort();
        break;
    }
  });

  if (_chatService.status.value.isSuccess) {
    SchedulerBinding.instance.addPostFrameCallback(
      (_) => _ensureScrollable(),
    );
  } else {
    _statusSubscription = _chatService.status.listen((status) {
      if (status.isSuccess) {
        SchedulerBinding.instance.addPostFrameCallback(
          (_) => _ensureScrollable(),
        );
      }
    });
  }

  super.onInit();
}