54

I have a dynamic x and I would like to assign x to T s if x is T, and otherwise assign null to s. Specifically, I would like to avoid having to type x twice, and to avoid creating a temporary. (For example, I don't want to have to write String s = map['key'] is String ? map['key'] : null; over and over, because I will have many such expressions.) I don't want there to be any possibility of a runtime error.

The following works:

class Cast<T> {
  T f(x) {
    if (x is T) {
      return x;
    } else {
      return null;
    }
  }
}

// ...

dynamic x = something();
String s = Cast<String>().f(x);

Is there a syntactically nicer way to do this?

7 Answers 7

84

Dart 2 has generic functions which allows

T? cast<T>(x) => x is T ? x : null;
dynamic x = something();
String s = cast<String>(x);

you can also use

var /* or final */ s = cast<String>(x);

and get String inferred for s

6
  • 3
    You should also be able to do String s = cast(x); and get the type parameter to cast inferred from the context.
    – lrn
    Commented Oct 4, 2018 at 11:58
  • 2
    Does this function still exit? Because the IDE does not seem to have this
    – dshukertjr
    Commented Mar 5, 2020 at 2:05
  • 2
    where is this function defined ?
    – IulianT
    Commented Apr 16, 2021 at 13:05
  • 2
    @LeresAldtai in my answer ;-) You need to define it yourself. Commented Apr 16, 2021 at 13:51
  • 3
    If you turn on null safety in dart. It'd be T? cast<T>(x) => x is T ? x : null; Commented Sep 1, 2021 at 14:55
21

I use the following utility function, which allows for an optional fallback value and error logging.

T? tryCast<T>(dynamic x, {T? fallback}){
    try{
        return (x as T);
    }
    on CastError catch(e){
        print('CastError when trying to cast $x to $T!');
        return fallback;
    }
}
var x = something();
String s = tryCast(x, fallback: 'nothing');
2
  • How can that return T instead of T? if fallback is optional? If fallback is omitted and x is! T, then won't it return a null? I'm guessing something has changed in dart over the years.
    – Jobu
    Commented Aug 20, 2023 at 15:46
  • 1
    @Jobu Yes, the previous answer was written long before sound null-safety was a thing. I have edited it to be null safe.
    – Magnus
    Commented Aug 20, 2023 at 17:10
15

I'm using those with Dart null safety (Dart SDK >= 2.12):

T? castOrNull<T>(dynamic x) => x is T ? x : null;

T castOrFallback<T>(dynamic x, T fallback) => x is T ? x : fallback;
1
14

Just use the as keyword

final tweet = tweets[index] as Tweet;
3
  • does this return null if the type not match?
    – axunic
    Commented Mar 30, 2021 at 11:10
  • 24
    as is a forced type cast and is not safe Commented Apr 10, 2021 at 15:38
  • 3
    This cannot be used anywhere. It does not return null if the type is not the given one. Instead, it throws an error. You should use it only if you're sure about the type. Commented Jun 9, 2021 at 14:21
10

This hidden gem was provided by one of Dart-Lang's maintainers:

extension AsExtension on Object? {
  X as<X>() => this as X;
  X? asOrNull<X>() {
    var self = this;
    return self is X ? self : null;
  }
}

extension AsSubtypeExtension<X> on X {
  Y asSubtype<Y extends X>() => this as Y;
}

extension AsNotNullExtension<X> on X? {
  X asNotNull() => this as X;
}

// example
void main() {
  num? n = 1 as dynamic;
  n.as<int>().isEven;
  n.asSubtype<int>().isEven; // `n.asSubtype<String>()` is an error.
  n.asNotNull().floor();
  n.asOrNull<int>()?.isEven; // Corresponds to `(n as? int)?.isEven`.
}

NOTE: If your object is of type dynamic, you have to cast it Object? first. The explanation for this can be found here: first one by Erik, a dart maintainer @Google and the second by a community member. Basically it boils down to dart not calling extension methods on receives of one of the following three types: dynamic, Never, or void as stated here.

1
  • I like this answer, but I'd recommend changing the generic to X extends Object?. If you don't it's possible to coerce a dynamic type from this method. This can lead to runtime errors. For example: if you think you've coerce an int, and tried calling toDouble() on it. The analyzer won't complain, but it will throw an error when you run it.
    – mhrst
    Commented Nov 10, 2023 at 18:28
7

A combination of both prior two posts, without the logging.

Fallback defaults to null when not provided.

T cast<T>(dynamic x, {T fallback}) => x is T ? x : fallback;
1
  • 1
    It should be T? cast<T>(dynamic x, {T? fallback}) => x is T ? x : fallback;
    – Battlefury
    Commented Aug 16, 2022 at 11:45
3

CastError is deprecated, Instead use TypeError.

With null safety, you can try the below snippet. Where fallback is optional/nullable.

T? tryCast<T>(dynamic value, {T? fallback}) {
  try {
    return (value as T);
  } on TypeError catch (_) {
    return fallback;
  }
}

Or without fallback -

T? tryCast<T>(dynamic value) {
  try {
    return (value as T);
  } on TypeError catch (_) {
    return null;
  }
}

Usage -

final val = tryCast<String>(1) ?? "";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.