What is Sealed class in flutter with example 2024

In this blog, we will explore what is Sealed class in flutter with proper real time example in 2024.
Let's start How to use sealed class in flutter in real time project with example step by step.
 
Sealed class in flutter with example

What is Sealed class in flutter/Dart with example Step by Step in 2024

Sealed classes are using the sealed keyword before the class keyword. It's restrict the inheritance of class hierarchy and it's subclasses must be declared in the same file as the sealed class.

The main purpose of sealed classes is to avoid further extension or modification of a class.

It is used when the object have only one of the types from limited set, but cannot have any other type.

Imp. Note:

Sealed class constructors are private by default and cannot be allowed as non-private.

Sealed class are implicitly abstract.

Subclasses of sealed class are not implicitly abstract.

Sealed class can't be constructed.

Subclasses of sealed class can be constructed.

Why Sealed Class is better than Enum Class or Advantages and Disadvantages of Sealed and Enum Class?

Sealed Class:
  • Sealed classes represent a concrete set of classes.
  • Every subclasses of a sealed class can create multiple instances.
  • Every subclass of sealed class can have own set of constructor parameters.
  • Subclasses of sealed class can hold instance-specific data.
  • Sealed Class exhaustively handle all possible cases of subclasses.
  • Every Sealed Class can be used class or an object keyword to create sub classes of sealed class.
Enum Class:
  • Enum classes represent a concrete set of constant values.
  • Every Enum constant value can create only single instances.
  • Their is not any own set of constructor parameters.
  • Enum can't hold instance-specific data.
  • Enum Class can't allow exhaustively handle all possible cases of constant value.
  • Enum Class can be used constant value to create subtype of enum class.

Example and Use Case of Sealed Class?

sealed class Expr {}

class Add extends Expr {
  final int value1;
  final int value2;
  Add(this.value1, this.value2);
}

class Substract extends Expr {
  final int value1;
  final int value2;
  Substract(this.value1, this.value2);
}

class Multiply extends Expr {
  final int value1;
  final int value2;
  Multiply(this.value1, this.value2);
}

String getCalculation(Expr expr) {
  return switch (expr) {
    Add(value1: int value1,value2: int value2) => 'Add two number - ${value1+value2}',
    Substract(value1: int value1,value2: int value2) => 'Substract two number - ${value1-value2}',
    Multiply(value1: int value1,value2: int value2) => 'Multiply two number - ${value1*value2}'  
  };
}

void main(){
  final Expr add = Add(2,2);
  final Expr substract = Substract(2,2);
  final Expr multiply = Multiply(2,2);
  print(getCalculation(add));
  print(getCalculation(substract));
  print(getCalculation(multiply));
}

Output:

Add two number - 4
Substract two number - 0
Multiply two number - 4
  • In the above example i have created one Sealed class "Expr" and created 3 subclasses ("Add", "Substract" and "Multiply"). Each type of subclasses extended as a "Expr" sealed class.
  • Each subclassed have a constructor and used to pass value according to requirement you can pass according to your requirement like what you need to use.
  • Now i created "getCalculation" method inside this method i have used switch condition for check which type of subclasses called and also implemented logic (Addition, Substraction and Multiplication of two numbers) in each switch cases.
  • Now in "main" method i have called all subclasses with pass two number in each subclasses.
  • Sealed Classes allow compiler to alert a error when a switch statement does not exhaustively handle all possible cases of subclasses like below.
String getCalculation(Expr expr) {
 // ERROR: The switch statement is missing of the Multiply subclasses or a default case.
  return switch (expr) {
    Add(value1: int value1,value2: int value2) => 'Add two number - ${value1+value2}',
    Substract(value1: int value1,value2: int value2) => 'Substract two number - ${value1-value2}' 
  };
}
  • In this above code if you don't want use exhaustive switch statement or want to be able to add subclasses later without breaking or getting error in code, use the final modifier instead of sealed on the base class.
Imp. Note:
  • We can't instantiated of Base Sealed class like this :- Expr expr = Expr();
  • We can instantiated of Subclasses in Sealed Class like this :- Expr add = Add(2,2);

Real Time Example and Use Case of Sealed Class

sealed class ApiResponse {}

class Loading extends ApiResponse {}

class Success<T> extends ApiResponse {
final T data;
Success(this.data);
}

class Error extends ApiResponse {
final String errorMessage;
Error(this.errorMessage);
}
  • In this above example you can call this "ApiResponse" sealed class in your Api calling method  inside viewModel or controller class, now you can add your Api Response in this sealed sub classes (Loading, Success and Error), with the help of sealed classes you can categories your api response for better user experience.
  • After that in your main page you can use observer or collect method to observe the Api Responses with the help of switch statement for get the Api Response with the help of sealed sub classes. 


Reference Site

here you can learn more about Sealed class in flutter with example

Conclusion 

Sealed classes are nothing just restrict the inheritance of class hierarchy and it's subclasses must be declared in the same file as the sealed class.
Sealed Classes allow compiler to alert a error when a switch statement does not exhaustively handle all possible cases of subclasses.

So Finally, In this blog, we have explored what is Sealed class in flutter with proper real time example in 2024.
Oversimplified Coding

I am Shubhangam Upadhyay founder of Oversimplified Coding. My motive of this blog to help those developer are just start there carrier in coding line. We cover here Android, Kotlin, Core Java, Jetpack Compose and Flutter etc. related topics. I have 6+ Years of experience in Android Development and working on MNC company as a Senior Android Developer Position. I have worked on 5 different companies and experience on many different type of real time application project.

*

Post a Comment (0)
Previous Post Next Post