Flutter bloc update object state after async finish

Issue

I’m working with flutter and the bloc pattern. The Todo tutorial (https://bloclibrary.dev/#/fluttertodostutorial?id=bloc) explains the bloc very well.

But no I want to extend the example app with information about “object sync completed/running”. I’ve attached an image with my idea of how it should work.

flow

I think the following function is doing something similar – change complete bool. But how to change the function to change the bool of 1 obj after the async call and fire it directly to the UI. After obj 1 go to obj 2 and so on.

Stream<TodosState> _mapToggleAllToState() async* {
    if (state is TodosLoadSuccess) {
      final allComplete =
          (state as TodosLoadSuccess).todos.every((todo) => todo.complete);
      final List<Todo> updatedTodos = (state as TodosLoadSuccess)
          .todos
          .map((todo) => todo.copyWith(complete: !allComplete))
          .toList();
      yield TodosLoadSuccess(updatedTodos);
      _saveTodos(updatedTodos);
    }
  } 

I hope that you understand my explanation and can help me 🙂

Solution

I could solve my problem 🙂 I want to share it.

Feel free to add comments with feedback and tips!

  Stream<DocsState> _mapTodosSyncToState() async* {
    final todos = (state as TodosLoadSuccess).todos;
    await for (Todo syncTodo in Stream.fromIterable(todos)) {
      List<Todo> updatedTodos = (state as TodosLoadSuccess).todos.map((todo) {
        return todo.id == syncTodo.id
            ? syncTodo.copyWith(task: syncTodo.task + " SYNCING")
            : todo;
      }).toList();
      yield TodosLoadSuccess(updatedTodos);

      await Future.delayed(Duration(seconds: 3));

      updatedTodos = (state as TodosLoadSuccess).todos.map((todo) {
        return todo.id == syncTodo.id
            ? syncTodo.copyWith(task: syncTodo.task + " COMPLETE")
            : todo;
      }).toList();

      yield TodosLoadSuccess(updatedTodos);
    }

  }

Answered By – Dominik00000

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.