UnsupportedError: 'Mirrors are not supported.' in dart:mirrors during AOT compilation
0 reputation · 14 Dec 2022, 03:46 UTC
0 reputation · 14 Dec 2022, 03:46 UTC
Local development on the Dart VM with JIT compilation permits the use of dart:mirrors for runtime type inspection and dynamic class loading. When the same code is compiled for production using AOT (e.g., flutter build apk --release or dart compile exe), the mirror system is omitted from the binary. Executing the release build immediately throws the documented error:
UnsupportedError: 'Mirrors are not supported.'
This discrepancy surfaces only in release environments, causing silent failures that are hard to diagnose without explicit AOT testing.
The Dart team has not yet committed to a partial mirror implementation for AOT. Developers face a choice: invest in a restricted mirror subset, or continue to rely on static code generation (build_runner) and, in Dart 3, macros for compile‑time introspection.
dart:mirrors usage before release packaging?35275 reputation · 14 Dec 2022, 11:27 UTC
The error occurs because dart:mirrors is excluded from AOT-compiled binaries. The solution is to remove mirror dependencies and replace them with static alternatives before building release artifacts.
import 'dart:mirrors'; and dependencies that require it.json_serializable and freezed provide mirror-like functionality without runtime overhead.flutter build apk --release or dart compile exe and test on device during development to catch mirror-related errors.Add a static analysis rule to flag dart:mirrors imports. Create a analysis_options.yaml entry:
analyzer:
exclude:
- 'test/**'
linter:
rules:
- avoid_implicit_calls
- avoid_private_field_declarations
# Custom script to detect mirrors
script:
name: detect_mirrors
command: grep -r "import 'dart:mirrors'" lib/ || echo "No mirrors found"
The Dart team has indicated no plans to add mirror support to AOT compilation. Migration to static code generation remains the only viable path for production applications.
Use comments to ask for clarification. Post a solution as an answer.
6,950 reputation · 14 Dec 2022, 10:40 UTC
The error is triggered by executing a reflective API, not merely by importing dart:mirrors. A release binary can import the library and still run until code calls reflectClass, InstanceMirror, or similar, which makes the failure path-dependent and easy to miss in smoke tests. Pin the SDK with dart --version or flutter --version, add a minimal reflective call, build with dart compile exe or flutter build apk --release, and run the artifact to reproduce UnsupportedError. Do not treat the exception as recoverable; AOT removes the mirror implementation entirely, so wrap-or-catch is not a portability strategy.