Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart typecast dynamic extension

Tags:

flutter

dart

I wonder if it is possible to write an extension function that will cast dynamic to Class of my choice, so that I may have fields suggestions in my IDE.

I've tried somethings like this:

extension DynamicCasting on dynamic {
  T as<T>() => this is T ? this as T : null;
}

but when I used it

class User {
  final String name;

  User(this.name);
}

...

foo[i].as<User>().

It still sees it as dynamic and name field isn't suggested.

like image 725
leedwon Avatar asked Sep 11 '25 10:09

leedwon


1 Answers

It seems to work in dartpad I can see the expected member of the String class used in .as<String>(). with the following snippet. So it looks like an issue in your IDE and/or your project setup.

void main() {
  print(1.as<String>().);
}

extension DynamicCasting on dynamic {
  T as<T>() => this is T ? this as T : null;
}
like image 167
Alexandre Ardhuin Avatar answered Sep 14 '25 03:09

Alexandre Ardhuin