Dart VM ↔ Flutter: Is null safety enforced when passing data into widget build methods?
0 reputation · 23 Oct 2022, 01:15 UTC
0 reputation · 23 Oct 2022, 01:15 UTC
When a null‑unsafe Dart library is imported into a null‑safe Flutter application, the compiler issues a warning but does not prevent the library’s methods from being called at runtime. The Flutter framework’s Widget.build method is invoked via dynamic dispatch, which may bypass the Dart VM’s static type checks. The goal is to determine whether null safety is preserved across this integration boundary.
Key constraints include the presence of a null‑unsafe library, a null‑safe Flutter widget tree, and the dynamic nature of widget build calls. Uncertainty remains about whether the VM’s runtime type checks are sufficient to catch null dereferences originating from the library when they reach widget build methods.
Questions for investigation:
33775 reputation · 23 Oct 2022, 06:28 UTC
Yes. When null-safe Flutter code receives a value from a null-unsafe library, the Dart VM enforces null safety at the boundary. If that value is null and the receiving variable or parameter is non-nullable, the VM throws a TypeError at the crossing point. Flutter’s dynamic dispatch of Widget.build does not bypass these checks.
Widget.build is an ordinary instance method; the framework invokes it through normal element rebinding, not through a mechanism that disables the type system.This assumes the Flutter app uses Dart 2.12 or later with sound null safety enabled, and Flutter 2.0 or later (null-safe framework). If the legacy library and the app are both compiled with a pre-2.12 language version, null safety is not enforced at all.
dart analyze in the Flutter app. Legacy interop usually produces no static errors because legacy types are treated as nullable.build, pass a legacy-library return value into a non-nullable parameter, for example Text(legacyApi.title) where title is a legacy String.TypeError at the assignment or call site, not silent propagation into the widget tree.Is the null-unsafe library constrained to a pre-2.12 SDK in its pubspec.yaml (environment: sdk: '<3.0.0' without a lower null-safe bound)? If both sides target pre-null-safety Dart, the boundary checks described above do not apply, and the recommendation changes to migrating the library or adding manual null checks.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.