1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Flutter Bloc Errorhandling Streams

Discussão em 'Mobile' iniciado por Stack, Novembro 9, 2024 às 16:43.

  1. Stack

    Stack Membro Participativo

    I am was reading a Flutter Bloc Tutorial, where the Topic is a Todo App (https://bloclibrary.dev/tutorials/flutter-todos/). I think that coding style / architecture is extremely clean! I currently use a similar approach as in Bloc, Clean Architecture and Functional Programming.

    Now, when I currently call a repository method, I handle errors from the data-layer in a function programming style: res is a Either<Failure,Unit> in this case.

    void _onHabitDeleteHabit(HabitDeleteHabit event, Emitter<HabitState> emit) async {
    final res = await _deleteHabit(DeleteHabitParams(event.id));
    res.fold((l) => emit(HabitFailure(l.message)), (_) => add(HabitGetAllHabits()));
    }


    Back to the Bloc Tutorial. I see they handle errors only in the _onSubscriptionRequested() (The method is called during initialization, to subscribe to the TodoStream), but not any other methods like _onTodoDeleted:

    Future<void> _onSubscriptionRequested(
    TodosOverviewSubscriptionRequested event,
    Emitter<TodosOverviewState> emit,
    ) async {
    emit(state.copyWith(status: () => TodosOverviewStatus.loading));

    await emit.forEach<List<Todo>>(
    _todosRepository.getTodos(),
    onData: (todos) => state.copyWith(
    status: () => TodosOverviewStatus.success,
    todos: () => todos,
    ),
    onError: (_, __) => state.copyWith(
    status: () => TodosOverviewStatus.failure,
    ),
    );
    }


    Seemingly no error handling here?

    Future<void> _onTodoDeleted(
    TodosOverviewTodoDeleted event,
    Emitter<TodosOverviewState> emit,
    ) async {
    emit(state.copyWith(lastDeletedTodo: () => event.todo));
    await _todosRepository.deleteTodo(event.todo.id);
    }


    They added a small text: emit.forEach() is not the same forEach() used by lists. This forEach enables the bloc to subscribe to a Stream and emit a new state for each update from the stream.

    Does that mean that if an Error happens in a method like _onTodoDeleted, the errorhandling is done for ALL methods in _onSubscriptionRequested() under _onError?

    And if so, how could you do a specific error handling for a specific method, if you need to?

    Continue reading...

Compartilhe esta Página