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($id) -> $hashCode', '$runtimeType');

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

  send = MessageFieldController(
    _chatService,
    _userService,
    _settingsRepository,
    _authService,
    _myUserService,
    _sessionService,
    _notificationService,
    onChanged: _updateDraft,
    onCall: call,
    onKeyUp: (key) {
      if (send.field.controller.text.isNotEmpty) {
        return false;
      }

      if (key == LogicalKeyboardKey.arrowUp) {
        final previous = chat?.messages.lastWhereOrNull((e) {
          return e.value is ChatMessage && !e.value.id.isLocal;
        });

        if (previous != null) {
          if (previous.value.isEditable(chat!.chat.value, me!)) {
            editMessage(previous.value);
            return true;
          }
        }
      }

      return false;
    },
    onSubmit: ({double? donateOnly}) async {
      _stopTyping();

      if (chat == null) {
        return;
      }

      final String text;
      final List<ChatItem> repliesTo;
      final List<Attachment> attachments;
      final double donation;

      if (donateOnly != null) {
        text = '';
        repliesTo = [];
        attachments = [];
        donation = donateOnly;
      } else {
        text = send.field.text.trim();
        repliesTo = send.replied.map((e) => e.value).toList();
        attachments = send.attachments.map((e) => e.value).toList();
        donation = send.donation.value;
      }

      if (donation != 0) {
        if (_walletService.balance.value.sum.val < donation) {
          return _showBalanceExceeded();
        }

        final UserId? userId = user?.id;
        if (userId != null) {
          final MonetizationSettings? settings =
              _partnerService.monetization[userId]?.value;
          if (settings != null) {
            if (settings.donation?.enabled != true) {
              return _showDonationsDisabled();
            }

            final double minimum = settings.donation?.min.sum.val ?? 1;
            if (donation < minimum) {
              return _showDonationsMinimum();
            }
          }
        }
      }

      if (text.isNotEmpty ||
          attachments.isNotEmpty ||
          repliesTo.isNotEmpty ||
          donation != 0) {
        _chatService
            .sendChatMessage(
              chat?.chat.value.id ?? id,
              text: text.isEmpty ? null : ChatMessageText(text),
              repliesTo: repliesTo,
              attachments: attachments,
              donation: donation == 0
                  ? null
                  : Donation(id: DonationId.local(), amount: Sum(donation)),
            )
            .then(
              (_) => AudioUtils.once(
                AudioSource.asset('audio/message_sent.mp3'),
              ),
            )
            .onError<PostChatMessageException>(
              (_, _) {},
              test: (e) =>
                  e.code == PostChatMessageErrorCode.unknownAttachment,
            )
            .onError<PostChatMessageException>(
              (_, _) => _showBlockedPopup(),
              test: (e) => e.code == PostChatMessageErrorCode.blocked,
            )
            .onError<PostChatMessageException>(
              (_, _) => _showBalanceExceeded(),
              test: (e) => e.code == PostChatMessageErrorCode.notEnoughFunds,
            )
            .onError<PostChatMessageException>(
              (_, _) => _showDonationsDisabled(),
              test: (e) =>
                  e.code == PostChatMessageErrorCode.disabledDonation,
            )
            .onError<UploadAttachmentException>(
              (e, _) => MessagePopup.error(e),
            )
            .onError<ConnectionException>((e, _) {});

        if (donateOnly == null) {
          send.clear(unfocus: false);
        }

        chat?.setDraft();
      }
    },
  );

  send.onInit();

  PlatformUtils.isActive.then((value) => active.value = value);
  _onActivityChanged = PlatformUtils.onActivityChanged.listen((v) {
    active.value = v;

    if (v) {
      readChat(_lastSeenItem.value);
    }
  });

  _selectingWorker = ever(selecting, (bool value) {
    if (!value) {
      selected.clear();
    }
  });

  _onFocusChanged = PlatformUtils.onFocusChanged.listen((value) {
    if (!value) {
      _stopTyping();
    }
  });

  // Stop the [_typingSubscription] when the send field loses its focus.
  send.field.focus.addListener(_stopTypingOnUnfocus);

  search.focus.addListener(_disableSearchFocusListener);

  _searchDebounce = debounce(query, (String? query) async {
    status.value = RxStatus.loadingMore();

    if (query == null || query.isEmpty) {
      if (searching.value) {
        switchToMessages();
        status.value = RxStatus.success();
      }
    } else {
      _fragment = null;
      elements.clear();

      final Paginated<ChatItemId, Rx<ChatItem>>? fragment = await chat!
          .around(withText: ChatMessageText(query));

      _searchSubscription?.cancel();
      _searchSubscription = fragment!.updates.listen(
        null,
        onDone: () {
          _fragments.remove(fragment);
          _fragmentSubscriptions.remove(_searchSubscription?..cancel());

          // If currently used fragment is the one disposed, then switch to
          // the [RxChat.messages] for the [elements].
          if (_fragment == fragment) {
            switchToMessages();
          }
        },
      );

      _fragment = fragment;

      Log.debug(
        '_searchDebounce("$query") -> await fragment.around()...',
        '$runtimeType',
      );

      await _fragment!.around();

      Log.debug(
        '_searchDebounce("$query") -> await fragment.around()... done! Elements are -> ${_fragment!.items.values}',
        '$runtimeType',
      );

      elements.clear();
      _fragment!.items.values.forEach(_add);
      _subscribeFor(fragment: _fragment);
      _updateFabStates();

      status.value = RxStatus.success();
    }
  });

  HardwareKeyboard.instance.addHandler(_keyboardHandler);

  super.onInit();
}