简体   繁体   中英

Flutter bloc update object state after async finish

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.

流动

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:-)

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);
    }

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM