Dart auto casting to most recent type?

Viewed 94

Why myImageProvider has the type of Object, but not ImageProvider.

I know I can use if-else clause, just curious about how auto-casting works.

final myImageProvider = (debugAssetPath != null)
        ? AssetImage(debugAssetPath!)
        : FileImage(File(capturedImagePath));

Thank you.

2 Answers

Dart seems to have trouble resolving the generic ImageProvider<T>. As it cannot find a common base type it resolves to the base type of all dart objects - Object.

To fix it simply cast AssetImage to ImageProvider

final myImageProvider = (debugAssetPath != null)
        ? AssetImage(debugAssetPath!) as ImageProvider
        : FileImage(File(capturedImagePath));

The resulting myImageProvider will be of type ImageProvider<Object>, so you loose type safety for any subsequent calls to the methods of myImageProvider with regards to the key property.

Because Object is a root of the non-nullable Dart class hierarchy, every other non-Null Dart class is a subclass of Object.

Since in AssetImage and FileImage are a subclass of Object and its conditionally switch so for both Widget i.e class are commonly denote as Object.

Ref: https://api.flutter.dev/flutter/dart-core/Object-class.html

Related