6

In Dart, I understand how super works like this :

class Foo {
  Foo(int a, int b) {
    //Code of constructor
  }
}

class Bar extends Foo {
  Bar(int a, int b) : super(a, b);
}

I don't really get what is happening when super is used in the cubit(or blocs) classes of flutter_bloc.

I'm not understanding for example when the CounterCubit class extends Cubit : CounterCubit extends Cubit<CounterState> and the CounterState class can be used as a parameter for the cubit.

class CounterState {
  int counterValue;
  CounterState({@required this.counterValue});
}



class CounterCubit extends Cubit<CounterState> {
  CounterCubit() : super(CounterState(counterValue: 0));
}
Adel B-Lahlouh
  • 1,059
  • 1
  • 8
  • 20
flutter
  • 6,188
  • 9
  • 45
  • 78

1 Answers1

0

The super constructor calls the constructor of the parent class. The cubit in flutter_bloc is defined as.

abstract class Cubit<State> extends BlocBase<State> {
  Cubit(State initialState) : super(initialState);
}

The State is just a generic class type here and can be of any type you want. You can learn more about generics here A very simple code for making a counter cubit is.

class CounterCubit extends Cubit<int> {
   CounterCubit() : super(0);

}

The Cubit<int> means your State here is of type int and super(0) sets the initial value state value to "0" as your value is type int. So essentially the super constructor of a cubit takes in the value of the initial state.

In your case:

class CounterState {
  int counterValue;
  CounterState({@required this.counterValue});
}



class CounterCubit extends Cubit<CounterState> {
  CounterCubit() : super(CounterState(counterValue: 0));
}

The Cubit<CounterState> means your State here is of type CounterState (which is a class you declared yourself above) and super(CounterState(counterValue: 0)) initializes an object with counterValue=0 and that object is passed as the initial state via super constructor.

I hope this clarifies your question. Do let me know if my explanation was not clear enough for you

Abuzar Rasool
  • 79
  • 1
  • 9