nexo_core library

Use cases, Bloc/Cubit helpers, network, and data sources.

Classes

BaseHiveDataSource<T, ID>
Базовый класс для работы с Hive хранилищем.
BaseIsarDataSource
Базовый класс для работы с Isar хранилищем.
BaseRemoteDataSource
Базовый класс для удалённых источников данных.
BaseSecureStorageDataSource
Базовый класс для работы с защищённым хранилищем (Keychain/Keystore).
BaseSharedPreferencesDataSource
Базовый класс для работы с SharedPreferences.
Bloc<Event, State>
Takes a Stream of Events as input and transforms them into a Stream of States as output.
BlocBase<State>
An interface for the core functionality implemented by both Bloc and Cubit.
BlocBuilder<B extends StateStreamable<S>, S>
BlocBuilder handles building a widget in response to new states. BlocBuilder is analogous to StreamBuilder but has simplified API to reduce the amount of boilerplate code needed as well as bloc-specific performance improvements. Please refer to BlocListener if you want to "do" anything in response to state changes such as navigation, showing a dialog, etc...
BlocBuilderBase<B extends StateStreamable<S>, S>
Base class for widgets that build themselves based on interaction with a specified bloc.
BlocConsumer<B extends StateStreamable<S>, S>
BlocConsumer exposes a builder and listener in order react to new states. BlocConsumer is analogous to a nested BlocListener and BlocBuilder but reduces the amount of boilerplate needed. BlocConsumer should only be used when it is necessary to both rebuild UI and execute other reactions to state changes in the bloc.
BlocEventSink<Event extends Object?>
An ErrorSink that supports adding events.
BlocListener<B extends StateStreamable<S>, S>
Takes a BlocWidgetListener and an optional bloc and invokes the listener in response to state changes in the bloc. It should be used for functionality that needs to occur only in response to a state change such as navigation, showing a SnackBar, showing a Dialog, etc... The listener is guaranteed to only be called once for each state change unlike the builder in BlocBuilder.
BlocListenerBase<B extends StateStreamable<S>, S>
Base class for widgets that listen to state changes in a specified bloc.
BlocObserver
An interface for observing the behavior of Bloc instances.
BlocProvider<T extends StateStreamableSource<Object?>>
Takes a create function that is responsible for creating the Bloc or Cubit and a child which will have access to the instance via BlocProvider.of(context). It is used as a dependency injection (DI) widget so that a single instance of a Bloc or Cubit can be provided to multiple widgets within a subtree.
BlocSelector<B extends StateStreamable<S>, S, T>
BlocSelector is analogous to BlocBuilder but allows developers to filter updates by selecting a new value based on the bloc state. Unnecessary builds are prevented if the selected value does not change.
Change<State>
A Change represents the change from one State to another. A Change consists of the currentState and nextState.
Closable
An object that must be closed when no longer in use.
CreateCrudEntity<T>
Событие создания новой сущности.
Cubit<State>
A Cubit is similar to Bloc but has no notion of events and relies on methods to emit new states.
DeleteCrudEntity<T>
Событие удаления сущности по идентификатору.
DioClient
Обёртка над Dio с типизированными методами HTTP-запросов.
Emittable<State extends Object?>
An object that can emit new states.
EmittableStateStreamableSource<State>
A StateStreamableSource that can emit new states.
Emitter<State>
An Emitter is a class which is capable of emitting new states.
ErrorSink
A generic destination for errors.
InMemoryOutboxStore
Реализация OutboxStore в памяти; подходит для тестов и как значение по умолчанию. В продакшене используйте персистентное хранилище.
LoadCrudData<T>
Событие загрузки данных.
MultiBlocListener
Merges multiple BlocListener widgets into one widget tree.
MultiBlocObserver
A BlocObserver which supports registering multiple BlocObserver instances. This is useful when maintaining multiple BlocObserver instances for different functions e.g. LoggingBlocObserver, ErrorReportingBlocObserver.
MultiBlocProvider
Merges multiple BlocProvider widgets into one widget tree.
MultiRepositoryProvider
Merges multiple RepositoryProvider widgets into one widget tree.
NexoAdminCrudBloc<T, F>
Generic CRUD BLoC для админ-панелей.
NexoAdminRepository<T>
Интерфейс репозитория для CRUD-операций в админ-панели.
NexoAsyncCubit<T>
Готовый кубит типового экрана: источник данных fetch + NexoAsyncState.
NexoAsyncFailure<T>
Состояние ошибки: загрузка завершилась неудачно.
NexoAsyncIdle<T>
Состояние ожидания: данные ещё не запрашивались.
NexoAsyncLoading<T>
Состояние загрузки: данные запрошены, но ещё не получены.
NexoAsyncState<T>
Типичное состояние экрана / фичи: ожидание, загрузка, данные или Failure.
NexoAsyncSuccess<T>
Состояние успешной загрузки: данные получены.
NexoAuthInterceptor
Интерсептор для автоматической аутентификации запросов.
NexoBloc<Event, S>
Абстрактный базовый класс BLoC с поддержкой обработки ошибок и Result.
NexoBlocObserver
Наблюдатель за жизненным циклом BLoC/Cubit с логированием и отчётом об ошибках.
NexoCrudError<T, F>
Состояние ошибки.
NexoCrudLoading<T, F>
Состояние загрузки данных.
NexoCrudReady<T, F>
Состояние готовности: данные загружены и доступны.
NexoCrudState<T, F>
Состояние CRUD-операций (загрузка, готово, ошибка).
NexoCubit<S>
Абстрактный базовый класс Cubit с поддержкой обработки ошибок и управлением подписками.
NexoLoggingInterceptor
Интерсептор для логирования HTTP-запросов, ответов и ошибок.
NexoOutbox
Очередь офлайн-мутаций (паттерн outbox): действия пользователя попадают в локальную очередь мгновенно, а flush доставляет их на сервер, когда появится сеть.
NexoRequestIdInterceptor
Добавляет x-request-id к запросу и пишет его в логи ответа / ошибки.
NexoRetryInterceptor
Интерсептор для автоматических повторных попыток при ошибках сети.
NexoStreamUseCase<T, Params>
Базовый класс для UseCase, работающих с потоками данных.
NexoUseCase<T, Params>
Базовый класс для UseCase, выполняющих одну асинхронную операцию.
NexoUseCaseAnnotation
Аннотация для автоматической генерации реализации UseCase.
NexoValidators
Готовые валидаторы для форм.
NoParams
Заглушка для параметров UseCase, которые не требуют входных данных.
OptimisticUpdateResult<TState>
Результат выполнения оптимистичного обновления.
OutboxEntry
Элемент очереди офлайн-мутаций.
OutboxFlushResult
Итог прохода NexoOutbox.flush.
OutboxStore
Персистентное хранилище очереди; реализуйте поверх своей БД (готовые датасорсы пакета: Hive / Isar / Drift / secure storage).
PageChunk<T, Cursor>
Порция данных при постраничной загрузке.
PaginationController<T, Cursor>
Контроллер постраничной загрузки данных.
ReconnectingStreamService<T>
Сервис с автоматическим переподключением к потоку данных.
RepositoryProvider<T>
Takes a create function that is responsible for creating the repository and a child which will have access to the repository via RepositoryProvider.of(context). It is used as a dependency injection (DI) widget so that a single instance of a repository can be provided to multiple widgets within a subtree.
SearchCrudData<T>
Событие поиска по списку.
StateStreamable<State>
A Streamable that provides synchronous access to the current state.
StateStreamableSource<State>
A StateStreamable that must be closed when no longer in use.
Streamable<State extends Object?>
An object that provides access to a stream of states over time.
StreamFactory<T>
Фабрика для создания потока данных.
Transition<Event, State>
A Transition is the change from one state to another. Consists of the currentState, an event, and the nextState.

Enums

HttpMethod
Перечисление HTTP-методов для запросов.

Mixins

FailureSupport
Миксин, добавляющий поддержку преобразования ошибок в Failure.
NexoPaginatedMixin<T, Cursor>
Миксин для добавления пагинации в BLoC/Cubit.
SubscriptionMixin
Миксин для управления потоковыми подписками с возможностью отмены по ключу.

Extensions

HttpMethodExtension on HttpMethod
Расширение для HttpMethod (обратная совместимость).
NexoAsyncStateDataX on NexoAsyncState<T>
Расширение для удобного извлечения данных из NexoAsyncState.
NexoUseCaseRetryX on NexoUseCase<T, Params>
ReadContext on BuildContext
Exposes the read method.
SelectContext on BuildContext
Adds a select method on BuildContext.
WatchContext on BuildContext
Exposes the watch method.

Functions

cloneRequestOptions(RequestOptions options, {Map<String, dynamic>? headers, Map<String, dynamic>? extra}) → Options
Клонирует RequestOptions в новый Options, сохраняя метод, заголовки, extra и прочие параметры.
concurrentTransformer<E>() → EventTransformer<E>
Трансформер: обрабатывает события параллельно.
debounceRestartable<E>(Duration duration) → EventTransformer<E>
Трансформер: debounced restartable.
droppableTransformer<E>() → EventTransformer<E>
Трансформер: отбрасывает новые события во время обработки.
fetchCacheThenNetwork<T>({required Future<T?> loadCache(), required Future<T> loadNetwork(), Future<void> saveCache(T data)?}) → Future<T>
Сначала кэш, при отсутствии — сеть и опционально сохранение в кэш.
fetchNetworkThenCache<T>({required Future<T> loadNetwork(), required Future<void> saveCache(T data), Future<T?> onNetworkFailureLoadCache()?}) → Future<T>
Сначала сеть и сохранение в кэш; при ошибке — опционально устаревшие данные из кэша.
nexoExecute<T, S>({required void emit(S), required bool isDone, required Future<T> action(), S onLoading()?, required S onSuccess(T data), required S onError(Failure failure)}) → Future<void>
Выполняет асинхронную операцию и маппит результат в состояние.
nexoExecuteEither<T, S>({required void emit(S), required bool isDone, required Future<Result<T>> action(), S onLoading()?, required S onSuccess(T data), required S onError(Failure failure)}) → Future<void>
Выполняет асинхронную операцию, возвращающую Result, и маппит результат.
nexoSubscribe<T, S>({required Emitter<S> emit, required bool isDone, required Stream<T> stream(), S onLoading()?, required S onData(T data), required S onError(Failure failure)}) → Future<void>
Подписывается на Stream и маппит события в состояния.
nexoSubscribeEither<T, S>({required Emitter<S> emit, required bool isDone, required Stream<Result<T>> stream(), S onLoading()?, required S onData(T data), required S onError(Failure failure)}) → Future<void>
Подписывается на Stream<Result> и маппит результаты в состояния.
performOptimistic<TState, TResult>({required TState optimisticState, required TState rollbackState, required Future<TResult> action(), required TState onSuccess(TResult result)}) → Future<OptimisticUpdateResult<TState>>
Выполняет оптимистичное обновление состояния.
restartableTransformer<E>() → EventTransformer<E>
Трансформер: отменяет предыдущую обработку события при новом.
sequentialTransformer<E>() → EventTransformer<E>
Трансформер: обрабатывает события строго по очереди.

Typedefs

BlocBuilderCondition<S> = bool Function(S previous, S current)
Signature for the buildWhen function which takes the previous state and the current state and is responsible for returning a bool which determines whether to rebuild BlocBuilder with the current state.
BlocListenerCondition<S> = bool Function(S previous, S current)
Signature for the listenWhen function which takes the previous state and the current state and is responsible for returning a bool which determines whether or not to call BlocWidgetListener of BlocListener with the current state.
BlocWidgetBuilder<S> = Widget Function(BuildContext context, S state)
Signature for the builder function which takes the BuildContext and state and is responsible for returning a widget which is to be rendered. This is analogous to the builder function in StreamBuilder.
BlocWidgetListener<S> = void Function(BuildContext context, S state)
Signature for the listener function which takes the BuildContext along with the state and is responsible for executing in response to state changes.
BlocWidgetSelector<S, T> = T Function(S state)
Signature for the selector function which is responsible for returning a selected value, T, based on state.
EventHandler<Event, State> = FutureOr<void> Function(Event event, Emitter<State> emit)
An event handler is responsible for reacting to an incoming Event and can emit zero or more states via the Emitter.
EventMapper<Event> = Stream<Event> Function(Event event)
Signature for a function which converts an incoming event into an outbound stream of events. Used when defining custom EventTransformers.
EventTransformer<Event> = Stream<Event> Function(Stream<Event> events, EventMapper<Event> mapper)
Used to change how events are processed. By default events are processed concurrently.
LoggerCallback = void Function(String message)
Callback для логирования событий интерсептора.
NexoValidator<T> = String? Function(T? value)
Валидатор поля формы: текст ошибки либо null, если значение корректно.
RetryCondition = bool Function(DioException error, int retryAttempt)
Функция определения условия повторной попытки.
RetryDelayCalculator = Duration Function(int retryAttempt)
Функция расчёта задержки между попытками.
TokenExpiredCallback = Future<void> Function()
Callback, вызываемый при истечении срока действия сессии.
TokenGetter = Future<String?> Function()
Функция получения текущего токена аутентификации.
TokenRefresher = Future<String?> Function()
Функция обновления токена аутентификации.

Exceptions / Errors

ProviderNotFoundException
The error that will be thrown if Provider.of fails to find a Provider as an ancestor of the BuildContext used.