Given a class with final private field _bar:
class Foo() {
final Bar _bar;
    Foo({Bar bar}) : _bar = bar {
        //error: list cannot be used as setter, it is final
       _bar = new Bar();
    }
}
Attempting to set it in the parameter list results in this error
//error: default values of an object must be constant
Foo({Bar bar: new Bar()}) : _bar = bar ..
I'd like to keep the optional parameter so that I can inject mocks during unit tests. What is the best approach for this?
class Foo {
  final Bar _bar;
  Foo({Bar bar}) : _bar = bar != null ? bar : new Bar();
}
I recommend to use static methods when a logic is complex thing.
class Foo {
  final Object _field1;
  Foo({Object value1}) : this._field1 = _setUpField1(value1);
  static Object _setUpField1(Object value) {
    // Some complex logic
    return value;
  }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With