Search code examples
flutterdartconstructorsuper

Which Constructor to use? and Why? What is super used for?


Code Sample #1 (Is my interpretation correct for these codes)

class Weather extends Equatable {
  final String cityName;
  final double temperature;

  Weather({
    @required this.cityName,
    @required this.temperature,
  });

  @override
  List<Object> get props => [cityName, temperature];
}

Code Sample #2 (Here the code throws error for adding an 'overrride')

class Weather extends Equatable {
  final String cityName;
  final double temperature;

  Weather({
    @required this.cityName,
    @required this.temperature,
  }) : super([cityName, temperature]);
}

enter image description here Thanks for your help in advance.


Solution

  • What is super used for?

    The keyword super is used to call the base class constructor. When you have a base class, you have to call that constructor. By default, if you don't do it explicitly, the constructor with no parameters will be called. The most obvious instance of having to call the constructor explicitly is when the base class does not have an accessible constructor without parameters.

    Which Constructor to use? and Why?

    You use your constructor. You explicitly call the super constructor if you need to. If you don't need to, the default call is fine.

    What's wrong here?

    Not your question, but that's why you are here I guess. In your second example you are calling a constructor of your base class that simply does not exist or is not accessible for you. I don't know where you got the idea that might work. Maybe outdated documentation or tutorials? Wishful thinking? In general, with a base class that does define a constructor like that, it would work. Your base class does not, so it does not work.