RuntimeType<T> constructor
RuntimeType<T> ()
Create a new RuntimeType representing T
.
To create constant RuntimeTypes, use the RuntimeType.allowingDynamic constructor.
Normally, Type objects are opaque and cannot be used for actual logic. RuntimeType allows for operations such as sub- or super-type checking, type checks, and casting using a variable instead of a literal.
To use, replace your type literals with calls to the RuntimeType constructor:
// Before
final stringType = String;
// After
final stringType = RuntimeType<String>();
Though it adds support for some operations, RuntimeType is not a replacement for type literals. For example, it cannot be used as a type argument as they are required to be type literals. Additionally, RuntimeType can be used at runtime to perform operations on types but it cannot extract type information at runtime:
final something = 'foo' as dynamic;
RuntimeType<T> extractType<T>(T instance) => RuntimeType<T>();
final typeOfSomething = extractType(something); // Still dynamic
Implementation
RuntimeType()
: assert(
T != dynamic,
'A RuntimeType instance was created with dynamic as the type argument. This is most'
' likely a mistake. RuntimeType instances can be used at runtime, but cannot be'
' dynamically created and a common symptom of this is dynamic being implicitly passed as'
' a type argument. Try using explicit type parameters, the Object? type instead of'
' dynamic, or, if this is intentional, use the RuntimeType.allowingDynamic()'
' constructor.',
);