Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare final class in Dart to prevent extending from it?

Tags:

flutter

dart

In Java\Kotlin we have a String class that is final and immutable.

I tried to mark the class with final keyword but looks like it's not allowable.

So, I'm a little bit confusing, how to declare final class in Dart ?

Note: the case is - I want to instantiate this class outside, but forbid to extending it. So using the private constructor - it's not my case.

like image 423
Sergey Shustikov Avatar asked Dec 20 '25 09:12

Sergey Shustikov


1 Answers

Additionally to the approach of making the constructor private and instantiating your object via a static factory, you could use the package meta and annotate your final class as sealed:

  @sealed
  class Z{}

This will signal users of your package that this class should not be extended or implemented. For example in vscode trying to extend the class Z:

  class Z1 extends Z{}

results in the following warning:

The class 'Z' shouldn't be extended, mixed in, 
or implemented because it is sealed.
Try composing instead of inheriting, or refer 
to its documentation for more information.dart(subtype_of_sealed_class)

The issue will also be picked up by the dart analyzer:

$ dart analyze
Analyzing test...                      0.8s

 info • lib/src/test_base.dart:3:1 • 
 The class 'Z' shouldn't be extended, mixed in, or implemented because it
 is sealed. Try composing instead of inheriting, or refer to its 
 documentation for more information. • subtype_of_sealed_class

Update: Dart 3.0 introduces class modifiers. The modifier final prevents the extension and implementation of the class outside of the current library.

final class Z{}
like image 71
Dan R Avatar answered Dec 22 '25 00:12

Dan R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!