classdartmethodsfinal

Is it possible to declare a method as final in a class in Dart?


In Java one can declare a method within a class to prevent subclasses from overriding it.

For example:

class Foo {

   final void bar() {
     // some code here.
   }

}

Is there a similar construction in Dart?


Solution

  • package:meta provides a @nonVirtual annotation to disallow overriding methods.

    Note that annotations just provide hints to dart analyze. They won't actually prevent anything from violating the annotations, and they instead will cause warnings to be printed when analysis is performed.

    If you want to disallow derived classes entirely (at least outside of the Dart library, which usually means outside of the .dart file), as of Dart 3.0, you can use the final or sealed class modifiers. Unlike annotations, those modifiers will be enforced by the compiler.