Skip to content

Commit 3c988c9

Browse files
committed
feat: initial pwa_safe_area package
Reusable iOS-PWA safe-area fix for Flutter web (flutter/flutter#84833): re-assert viewport-fit=cover via MutationObserver + merge CSS env() insets into MediaQuery. Self-contained package:web/dart:js_interop interop with no-op native stubs. Includes example web app, bootstrap-JS template, tests, and a diagnostic skill.
0 parents  commit 3c988c9

23 files changed

Lines changed: 1005 additions & 0 deletions
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
---
2+
name: pwa-safe-area
3+
description: >-
4+
Fix missing iOS safe areas in a Flutter web PWA. Trigger when: iOS PWA safe
5+
area missing, env(safe-area-inset-*) reads zero, SafeArea does nothing on the
6+
home-screen web app, notch/home-indicator overlap on web, Flutter web
7+
viewport-fit=cover dropped, or pointer taps land offset in a standalone iOS
8+
PWA. Reference: flutter/flutter#84833.
9+
---
10+
11+
# pwa-safe-area
12+
13+
Flutter web breaks iOS safe areas in a home-screen (standalone) PWA two ways:
14+
the engine (1) sizes its view from `documentElement.clientHeight`/`clientWidth`
15+
(ignores `viewport-fit=cover`) and (2) rewrites the viewport meta at boot,
16+
dropping `viewport-fit=cover`, which zeroes every `env(safe-area-inset-*)`.
17+
Result: no safe areas + offset pointer. Fix = three layers; all are required.
18+
19+
## Apply the fix
20+
21+
Use the `pwa_safe_area` package, or copy the pattern.
22+
23+
1. **Bootstrap JS** — `web/flutter_bootstrap.js` (runs before engine boot;
24+
cannot be done from Dart). Copy `example_web/flutter_bootstrap.js`. It:
25+
- overrides `document.documentElement.clientHeight`/`clientWidth` getters to
26+
`window.innerHeight`/`innerWidth`;
27+
- installs a `MutationObserver` on `document.head` that re-appends
28+
`, viewport-fit=cover` whenever the meta `content` changes;
29+
- ends with `{{flutter_js}}` / `{{flutter_build_config}}` /
30+
`_flutter.loader.load();`.
31+
2. **index.html CSS** — viewport meta must contain `viewport-fit=cover`; add
32+
`html { height:100vh; width:100vw; overflow:hidden } body { margin:0 }`.
33+
3. **main.dart** — `setupViewportFit();` right after
34+
`WidgetsFlutterBinding.ensureInitialized()` (no-op on native; Dart backstop
35+
for the meta re-assert).
36+
4. **Wrap the app** — `MaterialApp(builder: (c, child) => PwaSafeArea(child:
37+
child ?? const SizedBox.shrink()))`. Merges CSS `env()` insets into
38+
`MediaQuery` per-side max vs engine `viewPadding`; pure passthrough off web.
39+
40+
## Diagnosis checklist
41+
42+
- **Viewport meta at runtime**: in devtools console,
43+
`document.querySelector('meta[name=viewport]').content` — must still contain
44+
`viewport-fit=cover` after boot. If it lost it, the engine rewrote it and the
45+
observer is missing/not installed.
46+
- **Display mode**: `window.matchMedia('(display-mode: standalone)').matches`
47+
must be `true` — the bug only bites the home-screen PWA, not a Safari tab.
48+
- **CSS probe values**: a hidden div with `padding: env(safe-area-inset-top)`
49+
etc., read via `getComputedStyle` — if all zero on a notched device in
50+
standalone mode, `viewport-fit=cover` is missing (layer 1/2 broken).
51+
- **MediaQuery**: `MediaQuery.paddingOf(context)` should be non-zero at the top
52+
on a notched device once `PwaSafeArea` is in place.
53+
54+
## Gotchas
55+
56+
- **The engine rewrites the meta late** — a one-shot re-append is not enough; the
57+
`MutationObserver` is mandatory to win the race.
58+
- **Bootstrap JS is not optional** — `setupViewportFit()` alone runs too late
59+
(after engine boot) and does not fix view sizing; keep both.
60+
- **`extendBody` / full-screen SafeArea** — if an outer `SafeArea` (or the app
61+
shell with `extendBody: true`) already consumes the bottom inset, an inner
62+
scrollable padding by `MediaQuery.paddingOf(...).bottom` double-counts. Take
63+
the inset once.
64+
- **Per-side max, not replace** — iOS may make the engine report a bogus partial
65+
inset; merge by `max(css, engine)` per side so neither zero nor a partial
66+
value wins over the real one.
67+
- **Re-verify after a Flutter upgrade** — layer 1 patches engine boot behavior;
68+
a new engine could change the rewrite/sizing details.

‎.fvmrc‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"flutter": "3.44.4"
3+
}

‎.gitignore‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Dart / Flutter
2+
.dart_tool/
3+
.packages
4+
build/
5+
pubspec.lock
6+
7+
# FVM
8+
.fvm/
9+
10+
# IDE
11+
.idea/
12+
*.iml
13+
.vscode/
14+
15+
# macOS
16+
.DS_Store

‎CHANGELOG.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Changelog
2+
3+
## 0.1.0
4+
5+
Initial release.
6+
7+
- `setupViewportFit()` — re-asserts `viewport-fit=cover` on the viewport meta
8+
tag and installs a `MutationObserver` to keep re-asserting it after the
9+
Flutter engine rewrites the tag at boot.
10+
- `safeAreaInsets` / `safeAreaInsetsStream` — read the live CSS
11+
`env(safe-area-inset-*)` values via a hidden probe element, updating on
12+
resize / orientation change / visual-viewport resize.
13+
- `PwaSafeArea` widget — merges the CSS insets into `MediaQuery` (per-side max
14+
vs the engine's `viewPadding`); a pure pass-through on non-web.
15+
- `mergeSafeAreaViewPadding` / `resolveSafeAreaPadding` — the pure merge math,
16+
exported for testing and advanced use.
17+
- Self-contained web interop via `package:web` + `dart:js_interop`; no-op stubs
18+
on native platforms (no dependency on `safe_area_insets`).
19+
- `example_web/flutter_bootstrap.js` template and a runnable Flutter web
20+
example.

‎LICENSE‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Zonily Jame Pablo Zamora
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

‎README.md‎

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
# pwa_safe_area
2+
3+
Make `env(safe-area-inset-*)` work in a **Flutter web app installed to the iOS
4+
home screen** (a standalone PWA). Re-asserts `viewport-fit=cover` after the
5+
engine drops it, and merges the real CSS safe-area insets into `MediaQuery` so
6+
`SafeArea`, the notch, and the home indicator are respected.
7+
8+
Battle-tested in a shipping iOS PWA. Self-contained (`package:web` +
9+
`dart:js_interop`) — no `dart:html`, no `safe_area_insets` dependency.
10+
11+
## The problem
12+
13+
On an iOS home-screen (standalone) PWA, Flutter web breaks safe areas in two
14+
ways (tracked as [flutter/flutter#84833][issue]):
15+
16+
1. **View sizing.** The engine sizes its view from
17+
`document.documentElement.clientHeight` / `clientWidth`, which **ignore**
18+
`viewport-fit=cover`. The Flutter view gets pushed under the status bar or
19+
leaves a blank band, and the hit-test grid drifts out of alignment with the
20+
real pointer (taps land in the wrong place).
21+
2. **Zeroed insets.** The engine **rewrites the viewport meta tag at boot**,
22+
dropping `viewport-fit=cover`. Without that directive iOS reports **zero**
23+
for every `env(safe-area-inset-*)`, so `MediaQuery.padding` is empty and
24+
`SafeArea` does nothing — content collides with the notch and the home
25+
indicator.
26+
27+
Net result: no safe areas plus pointer-offset bugs, specifically inside a
28+
standalone iOS PWA (a normal Safari tab is mostly unaffected).
29+
30+
## The three-layer fix
31+
32+
No single layer is enough; the fix is a stack:
33+
34+
| Layer | Where | What it does |
35+
|------|-------|--------------|
36+
| **1. Bootstrap JS** | `web/flutter_bootstrap.js` | Overrides `clientHeight` / `clientWidth` → `window.innerHeight` / `innerWidth`, **and** installs a `MutationObserver` that re-appends `viewport-fit=cover` every time the engine rewrites the meta. Must run before the engine boots — this is why it is JS, not Dart. |
37+
| **2. CSS** | `web/index.html` | `html { height: 100vh; width: 100vw; overflow: hidden }` — sizes the document to the layout viewport so the getter overrides have a stable basis and overscroll reveals no blank band. |
38+
| **3. Dart** | this package | `PwaSafeArea` reads the live CSS `env()` insets via a hidden probe and merges them into `MediaQuery` (per-side **max** vs the engine's `viewPadding`). `setupViewportFit()` is a belt-and-suspenders Dart backstop for the meta re-assert. |
39+
40+
## Install
41+
42+
```yaml
43+
dependencies:
44+
pwa_safe_area: ^0.1.0
45+
```
46+
47+
Then apply all three layers.
48+
49+
### Layer 1 — `web/flutter_bootstrap.js`
50+
51+
Create `web/flutter_bootstrap.js` (this **overrides** Flutter's auto-generated
52+
bootstrap; the `{{...}}` tokens are substituted at build time). A ready-to-copy
53+
copy ships in this repo at [`example_web/flutter_bootstrap.js`](example_web/flutter_bootstrap.js):
54+
55+
```js
56+
// (1) The engine sizes its view from documentElement.clientHeight/clientWidth,
57+
// which ignore viewport-fit=cover. Override them to the visual-viewport size so
58+
// the Flutter view fills the screen and the hit-test grid stays aligned.
59+
Object.defineProperty(document.documentElement, 'clientHeight', {
60+
get: () => window.innerHeight,
61+
});
62+
Object.defineProperty(document.documentElement, 'clientWidth', {
63+
get: () => window.innerWidth,
64+
});
65+
66+
// (2) The engine rewrites the viewport meta at boot WITHOUT viewport-fit=cover,
67+
// which zeroes every env(safe-area-inset-*). Re-append it on every change.
68+
(() => {
69+
const ensureViewportFit = () => {
70+
const meta = document.querySelector('meta[name=viewport]');
71+
if (meta && !meta.content.includes('viewport-fit=cover')) {
72+
meta.content += ', viewport-fit=cover';
73+
}
74+
};
75+
ensureViewportFit();
76+
new MutationObserver(ensureViewportFit).observe(document.head, {
77+
subtree: true,
78+
childList: true,
79+
attributes: true,
80+
attributeFilter: ['content'],
81+
});
82+
})();
83+
84+
{{flutter_js}}
85+
{{flutter_build_config}}
86+
87+
_flutter.loader.load();
88+
```
89+
90+
### Layer 2 — `web/index.html`
91+
92+
Ensure the viewport meta includes `viewport-fit=cover` and add the CSS:
93+
94+
```html
95+
<meta name="viewport"
96+
content="width=device-width, initial-scale=1.0, viewport-fit=cover">
97+
98+
<!-- iOS home-screen PWA -->
99+
<meta name="apple-mobile-web-app-capable" content="yes">
100+
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
101+
102+
<style>
103+
html { height: 100vh; width: 100vw; overflow: hidden; }
104+
body { margin: 0; }
105+
</style>
106+
```
107+
108+
### Layer 3 — Dart
109+
110+
Call `setupViewportFit()` early, and wrap your app in `PwaSafeArea`:
111+
112+
```dart
113+
import 'package:flutter/material.dart';
114+
import 'package:pwa_safe_area/pwa_safe_area.dart';
115+
116+
void main() {
117+
WidgetsFlutterBinding.ensureInitialized();
118+
setupViewportFit(); // no-op on native, so no kIsWeb guard needed
119+
runApp(const MyApp());
120+
}
121+
122+
class MyApp extends StatelessWidget {
123+
const MyApp({super.key});
124+
125+
@override
126+
Widget build(BuildContext context) {
127+
return MaterialApp(
128+
builder: (context, child) =>
129+
PwaSafeArea(child: child ?? const SizedBox.shrink()),
130+
home: const HomePage(),
131+
);
132+
}
133+
}
134+
```
135+
136+
That's it — `SafeArea`, `MediaQuery.paddingOf`, etc. now see the real insets.
137+
138+
## API
139+
140+
| Symbol | Description |
141+
|--------|-------------|
142+
| `PwaSafeArea({required Widget child})` | Wraps `child`, merging the CSS insets into `MediaQuery`. Pure pass-through on non-web. |
143+
| `void setupViewportFit()` | Re-asserts `viewport-fit=cover` and installs a `MutationObserver`. No-op on native. |
144+
| `EdgeInsets get safeAreaInsets` | The current CSS `env(safe-area-inset-*)` values (`EdgeInsets.zero` on native). |
145+
| `Stream<EdgeInsets> get safeAreaInsetsStream` | Broadcast stream of inset updates on resize / orientation / visual-viewport resize (empty on native). |
146+
| `EdgeInsets mergeSafeAreaViewPadding({cssInsets, engineViewPadding})` | Pure: per-side max of CSS and engine view padding. |
147+
| `EdgeInsets resolveSafeAreaPadding({mergedViewPadding, viewInsets})` | Pure: `viewPadding - viewInsets`, clamped ≥ 0. |
148+
149+
### The merge, precisely
150+
151+
```dart
152+
merged.side = max(cssInset.side, engineViewPadding.side); // per side
153+
padding.side = clamp(merged.side - viewInsets.side, 0, ∞); // per side
154+
```
155+
156+
Taking the per-side **maximum** is deliberate: iOS can make the engine report a
157+
bogus *partial* inset. A package that trusts either source alone silently
158+
disables itself in that case; the max always keeps the safer (larger) value.
159+
160+
## Design notes
161+
162+
- **Self-contained interop.** Uses `package:web` + `dart:js_interop` — the
163+
modern interop. `dart:html` is deprecated and `dart:js_util` was removed in
164+
Dart 3.12, so this package depends on neither.
165+
- **No-op stubs on native, never throwing.** Conditional imports give native
166+
and VM builds a harmless no-op passthrough. This is a deliberate departure
167+
from `safe_area_insets`, whose native stub throws — a passthrough lets you
168+
call the API unconditionally without `kIsWeb` guards.
169+
170+
## Limitations
171+
172+
- **iOS home-screen (standalone) PWA focused.** That is the environment where
173+
`env(safe-area-inset-*)` reads zero under Flutter web; the fix targets it.
174+
The layers are harmless elsewhere but bring no benefit in a normal browser
175+
tab, on Android, or on native.
176+
- **Engine-version caveat.** Layer 1 patches engine boot behavior via DOM
177+
getter overrides and a meta observer. It is robust against the current
178+
rewrite behavior, but a future Flutter engine that changes how it sizes the
179+
view or rewrites the meta could shift the details — re-verify on-device after
180+
a Flutter upgrade.
181+
- **`setupViewportFit()` is not a substitute for layer 1.** The bootstrap JS
182+
must run before the engine boots; the Dart call is only a late backstop.
183+
184+
## Reference
185+
186+
- Flutter issue: [flutter/flutter#84833][issue]
187+
188+
[issue]: https://github.com/flutter/flutter/issues/84833
189+
190+
## License
191+
192+
MIT © 2026 Zonily Jame Pablo Zamora

‎analysis_options.yaml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
include: package:flutter_lints/flutter.yaml
2+
3+
analyzer:
4+
language:
5+
strict-casts: true
6+
strict-raw-types: true
7+
8+
linter:
9+
rules:
10+
public_member_api_docs: true

‎example/.fvmrc‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"flutter": "3.44.4"
3+
}

0 commit comments

Comments
 (0)