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
Parameter | Optional/Required | Description |
---|---|---|
source | required | The source set to adapt. |
newSet | optional | A 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,
- We create a Set
mixedSet
with elements of various types. - We use the
Set.castFrom
static method to cast it to a set of strings. - The method adapts the source set to the new type.
- 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,
- We create a Set
numberSet
with elements 1, 2, and 3. - We use the
Set.castFrom
static method to cast it to a set of integers. - The method adapts the source set to the new type.
- 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.