ContactsBloc constructor

ContactsBloc()

Implementation

ContactsBloc() : super(const ContactsState()) {
  on<GetContacts>((event, emit) async {
    emit(state.copyWith(isLoading: true));

    List<Contact> contacts = [];

    bool permission = false;

    if (!event.getIfHasPermission) {
      permission = await FlutterContacts.requestPermission(readonly: true);
      emit(state.copyWith(hasPermission: permission));
      await LocalStorage.setContactPermission(permission);
    }
    permission = LocalStorage.getContactPermission();
    emit(state.copyWith(hasPermission: permission));
    if (!permission && !event.getIfHasPermission) {
      await openAppSettings();
    }
    if (permission) {
      contacts = await FlutterContacts.getContacts(
        withProperties: true,
        withAccounts: true,
        withPhoto: true,
        withThumbnail: true,
        sorted: true,
      );
      emit(state.copyWith(
        allContacts: contacts,
        searchContacts: contacts,
      ));
    }
    emit(state.copyWith(isLoading: false));
  });

  on<SetSearchText>(
    (event, emit) {
      emit(state.copyWith(isLoading: true));

      List<Contact> searchContacts = [];

      if (event.searchText.isNotEmpty) {
        searchContacts = state.allContacts.where(
          (element) {
            return element.displayName
                    .toLowerCase()
                    .contains(event.searchText.toLowerCase()) ||
                element.phones
                    .where(
                      (element) => element.number
                          .toString()
                          .replaceAll("-", "")
                          .replaceAll("(", "")
                          .replaceAll(")", "")
                          .contains(event.searchText.toLowerCase()),
                    )
                    .isNotEmpty;
          },
        ).toList();
      } else {
        searchContacts = state.allContacts;
      }

      emit(state.copyWith(
        searchContacts: searchContacts,
        searchText: event.searchText,
      ));

      emit(state.copyWith(isLoading: false));
    },
  );
}