Search code examples
flutterbloc

Tryin to understand bloc, are you supposed to create multiple instances of the same bloc?


If you have a to-do list, is it okay to create multiple instances of the same bloc like this, where im giving each to-do it's own instance and state. Or am I supposed to put all of them inside it's own bloc?

todos.map((e) {
  return Padding(
    padding: const EdgeInsets.only(bottom: 8.0),
    child: BlocProvider(
      create: (context) => TodoBloc(),
      child: TodoItem(todo: e),
    ),
  );
}).toList(),

Solution

  • Suppose both scenarios works, so what is the difference ?

    The difference actually related to performance, imagine that:

    Each task has its own Bloc object that manages its state and so on.

    todos.map((e) {
      return Padding(
        padding: const EdgeInsets.only(bottom: 8.0),
        child: BlocProvider(
          create: (context) => TodoBloc(),
          child: BlocConsumer(//to use the provided bloc
    
               child: TodoItem(todo: e)),
        ),
      );
    }).toList(),
    

    So, every task requires a Bloc provider and a Bloc Consumer, which equal to NoTasks * 2 (objects in device memory).

    The other scenario, is to provide a Bloc object for all of the existing tasks to manage their state,

    BlocProvider(
    BloConsumer(
    List<Tasks>
    
    // if a task is checked to be marked completed
    // pass its name or id to the bloc to change its state
    )
    )
    

    So, only two objects in memory manages the states of the whole tasks, which increases the performance.

    It's completely revolves around the performance.

    Hope it helps you.