Best way to persist multiple variables within the same BLoC

Viewed 190

I have a BLoC (using flutter_bloc) that has multiple possible states and (now, it will probably become more as I add more features to this part of the UI) three different variables it needs to persist between state changes, unless explicitly changed. I find this happens frequently when making apps and I'm looking for a better solution than manually copying the different variables via each state's constructor on every different state change (lots of boilerplate) or (ab)using BLoC observers to copy the variables which haven't changed between different states.

My best idea is to create a single model to hold the different variables and pass the model between state changes, but this feels wrong. What do you guys do?

1 Answers

For now I chose to provide the last state as an argument to the superclass constructor and copy the values like that. The only issue I can see with this is they can't be nulled unless you nullify the state to copy from and supply all the other non-null arguments when calling.

abstract class TaskEditorState {
  final TaskModel task;
  final TaskModel original;
  final bool adjustByEstimate;
  TaskEditorState({
    @required TaskEditorState copyFrom,
    TaskModel original,
    TaskModel task,
    bool adjustByEstimate,
  })  : this.original = original ?? copyFrom?.original,
        this.task = task ?? copyFrom?.task,
        this.adjustByEstimate =
            adjustByEstimate ?? copyFrom?.adjustByEstimate;
}

class TaskEditorInitial extends TaskEditorState {
  TaskEditorInitial(
      {@required TaskModel task,
      @required TaskModel original,
      @required adjustByEstimate})
      : super(
            copyFrom: null,
            task: task,
            original: original,
            adjustByEstimate: adjustByEstimate);
}

class TaskEditorNameEdited extends TaskEditorState {
  TaskEditorNameEdited({@required TaskEditorState copyFrom})
      : super(copyFrom: copyFrom);
}

// ...

class TaskEditorCreatedTask extends TaskEditorState {
  TaskEditorCreatedTask(
      {@required TaskEditorState copyFrom, TaskModel task})
      : super(copyFrom: copyFrom, task: task);
}

// ...
Related