skip to Main Content

I’m looking through of sealed usage in my projects, and I can’t figure it out.

The "sealed" modifier states "The sealed modifier prevents a class from being extended or implemented outside its own library. Sealed classes are implicitly abstract." on dart.dev page.

// sign_result_entity.dart

sealed class SignResult extends Equatable {
  @override
  List<Object?> get props => [];
}
// sign_result_test.dart

import 'sign_result_entity.dart';

class UniqueSignResult extends SignResult {}

The problem is – I’m trying to implement sealed class outside of file, and I get the next message:

enter image description here

The file located in a same directory, same folder.

enter image description here

I believe the "library" means a different thing than we would expect.
Extending it in a same file works fine.

2

Answers


  1. Every Dart file (plus its parts) is a library, even if it doesn’t use a library directive

    Since every Dart file is a library, you cannot extend SignResult from another file.
    The only way to do that is to use part/part of.

    part 'sign_result_test.dart';
    
    sealed class SignResult extends Equatable {
      @override
      List<Object?> get props => [];
    }
    
    part of 'sign_result_entity.dart';
    
    class UniqueSignResult extends SignResult {}
    
    Login or Signup to reply.
  2. To create a known, enumerable set of subtypes, use the sealed
    modifier. This allows you to create a switch over those subtypes that
    is statically ensured to be exhaustive.

    The sealed modifier prevents a class from being extended or
    implemented outside its own library. Sealed classes are implicitly
    abstract.

    That’s why you can’t extend the class outside its library.

    You can read about sealed classes in this article :

    Sealed Classes in Dart: Unlocking Powerful Features

    or

    Dart Documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search