Dart Set.castFrom()
Syntax & Examples


Set.castFrom() static-method

The `castFrom` static method in Dart adapts a source set of type S to be a new set of type T.


Syntax of Set.castFrom()

The syntax of Set.castFrom() static-method is:

 Set<T> castFrom<S, T>(Set<S> source, { Set<R> newSet() }) 

This castFrom() static-method of Set adapts source to be a Set.

Parameters

ParameterOptional/RequiredDescription
sourcerequiredThe source set to adapt.
newSetoptionalA function that creates a new set of type R. If not provided, a default implementation is used.

Return Type

Set.castFrom() returns value of type Set<T>.



✐ Examples

1 Cast mixed set to set of strings

In this example,

  1. We create a Set mixedSet with elements of various types.
  2. We use the Set.castFrom static method to cast it to a set of strings.
  3. The method adapts the source set to the new type.
  4. We print the result to standard output.

Dart Program

void main() {
  Set<dynamic> mixedSet = {1, 'apple', true};
  Set<String> result = Set.castFrom(mixedSet);
  print('Result: $result');
}

Output

Result: {1, apple, true}

2 Cast set of numbers to set of integers

In this example,

  1. We create a Set numberSet with elements 1, 2, and 3.
  2. We use the Set.castFrom static method to cast it to a set of integers.
  3. The method adapts the source set to the new type.
  4. We print the result to standard output.

Dart Program

void main() {
  Set<num> numberSet = {1, 2, 3};
  Set<int> result = Set.castFrom(numberSet);
  print('Result: $result');
}

Output

Result: {1, 2, 3}

Summary

In this Dart tutorial, we learned about castFrom() static-method of Set: the syntax and few working examples with output and detailed explanation for each example.