Home > OS >  Loose coupling in Dart
Loose coupling in Dart

Time:02-13

I was trying to implement loose coupling in one of my Flutter projects. It was not able to find the method. Have replicated the same in a simple Dart code, how can I fix this, and is there some way to achieve loose coupling in Dart?

abstract class A{}

class B extends A{
  void help(){
    print("help");
  }
}

class C {
  A b;
  C({required this.b});
  void test(){
     b.help();
  }
 
  
}

void main() {
 var c = C(b:B());
  c.test();
  
}

Giving error at b.help(), the method does on exist.

Exact error

The method 'help' isn't defined for the type 'A'.

CodePudding user response:

b is known to be of type A, and the A interface does not provide a help method.

I don't know exactly what your definition of "loose coupling" is (it'd be better to describe a specific problem that you're trying to solve), but if you want help to be callable on type A, then you must add it to the A interface.

You alternatively could explicitly downcast b to B with a runtime check:

class C {
  A b;
  C({required this.b});
  void test() {
    // Shadow `this.b` with a local variable so that the local
    // variable can be automatically type-promoted.
    final b = this.b;
    if (b is B) {
      b.help();
    }
  }
}

Or if you want duck typing, you could declare (or cast) b as dynamic:

class C {
  dynamic b;
  C({required this.b});
  void test() {
    try {
      b.help();
    } on NoSuchMethodError {}
  }
}

although I would consider the last form to be bad style.

  • Related