Flutter BLoC/Cubit STATE class best practices
Try using Cubit, it simplifies the code a lot.
I would probably create a function addToDo(todoItem)
and removeToDo(todoItem)
in the cubit class that updates the list and emits the change. The list variable would be in the Cubit, and you will refer to this list from the Widget by using context.read<TodoCubit>().todoList
.
And you will use the functions like so: context.read<TodoCubit>().addToDo(todoItem)
I've written a tutorial for best approach for Cubit implementation Flutter | Firebase Authentication with Cubit (Bloc) — Tutorial 1 of 2
I think this article will be a lot of help for you. Take a look 🤓
rejy11
Senior Software Developer working on the Radiology Information System for NHS Wales Informatics Service.
Updated on November 28, 2022Comments
-
rejy11 over 1 year
I'm new to using Bloc and Cubit so I'm trying to figure out some best practices specifically with the State component. I have a simple Todos app where the Todos can be in multiple different states:
part of 'todos_cubit.dart'; abstract class TodosState extends Equatable { const TodosState(); @override List<Object> get props => []; } class TodosLoading extends TodosState {} class TodosLoaded extends TodosState { final List<Todo> todos; TodosLoaded(this.todos); @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is TodosLoaded && listEquals(other.todos, todos); } @override int get hashCode => todos.hashCode; } class TodosEmpty extends TodosState {} class TodosError extends TodosState { final String error; TodosError(this.error); @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is TodosError && other.error == error; } @override int get hashCode => error.hashCode; }
My question is, should I keep the
List<Todo> todos
in theTodosLoaded
subclass or should it be moved to the base class? My thoughts are that by moving it to the base class, it would make myTodosEmpty
state redundant because I could simple check to see if the list of todos is empty in the UI. If this is the case, should I also move theString error
to the base class?Im sure there are pros and cons to each approach, just hoping to bounce ideas off anyone with more experience with Bloc.
-
rejy11 about 3 yearsI am using Cubit already. I was just wondering about best practices when designing each of my states and whether the list of todos should be in TodosState or TodosLoaded.