Search code examples
flutterdesign-patternsblocflutter-bloc

Flutter bloc pattern


I'm learning bloc pattern. I could not understand what is the usecase of this toString function in bloc pattern. Ok I did convert the constructor to string and passed it the counter, so what?! why should I even do something like that?!

class CounterState extends Equatable {
  final int counter;

  const CounterState({
    required this.counter,
  });

  factory CounterState.initial() {
    return const CounterState(counter: 0);
  }

  // THIS FUNCTION 
  @override
  String toString() => 'CounterState(counter: $counter)';
  //

  CounterState copyWith({
    int? counter,
  }) {
    return CounterState(
      counter: counter ?? this.counter,
    );
  }

  @override
  List<Object> get props => [counter];
}

Solution

  • https://api.flutter.dev/flutter/dart-async/TimeoutException/toString.html

    Some classes have a default textual representation, often paired with a static parse function (like [int.parse]). These classes will provide the textual representation as their string representation.

    Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

    sometimes I overwrite it to make it easier to debug. For example, when there are multiple arrays, I overwrite toString to not display the entire contents of the arrays, but only the number of elements in them.