Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Bloc: BlocBuilder not getting called after an update, ListView still displays old data

Tags:

flutter

bloc

I'm using flutter_bloc for state management and landed on this issue. When updating a field and saving it, the BlocBuilder is not refreshing the page. It is working fine when Adding or Deleting. I'm not sure what I'm doing wrong here.

Even if I go to a different screen and returning to this screen it still displays the old data even though the file was updated.

I spent more than 2 hours trying to debug this to no avail. I tried initializing the updatedTodos = [] then adding each todo one by one, to see if that does something, but that didn't work either.

Any help here would be appreciated.

TodosBloc.dart:

Stream<TodosState> _mapUpdateTodoToState(
    TodosLoaded currentState,
    UpdateTodo event,
  ) async* {     
        if (currentState is TodosLoaded) {
        final index = currentState.Todos
            .indexWhere((todo) => event.todo.id == todo.id);
        final List<TodoModel> updatedTodos =
            List.from(currentState.todos)
              ..removeAt(index)
              ..insert(index, event.todo);

        yield TodosLoaded(updatedTodos);
        _saveTodos(updatedTodos);
      }
  }

todos_screen.dart:

...
Widget build(BuildContext context) {
    return BlocBuilder(
      bloc: _todosBloc,
      builder: (BuildContext context, TodosState state) {
        List<TodoModel> todos = const [];
        String _strings = "";
        if (state is TodosLoaded) {
          todos = state.todos;
        }
        return Expanded(
          child: ListView.builder(
            itemCount: todos.length,
            itemBuilder: (BuildContext ctnx, int index) {
              return Dismissible(
                key: Key(todo.toString()),
                child: DetailCard(
                  todo: todos[index],
                ),
              );
            },
          ),
        );
...

I'm expecting when the BlocBuilder to be called and refreshed the ListView.

like image 744
Kajan Nallathamby Avatar asked Dec 05 '22 10:12

Kajan Nallathamby


1 Answers

I was able to resolve this with the help of Felix Angelov on github. The problem is that I'm extending Equatable but not passing the props to the super class in the TodoModel class. I had to update the constructor of the TodoModel with a super([]).

like image 130
Kajan Nallathamby Avatar answered May 10 '23 01:05

Kajan Nallathamby