😃

Flutter Webでbodyにアクセスする

2021/11/22に公開

Flutter Webでアプリを開発していると、なかなか無いはずですが、bodyエレメントにアクセスしたくなる瞬間があるかもしれません。

そんなときは、下記のように取得することができます。

// get flutter web's main view
final fltGlassPane = html.window.document.querySelector('flt-glass-pane');
final body = fltGlassPane?.parent;

flt-glass-paneは、執筆地点ではhtmlでもcanvas-kitによる描画のどちらでも、FlutterのViewの親になっています。

https://github.com/flutter/website/blob/main/src/release/breaking-changes/platform-views-using-html-slots-web.md

Flutter now renders all web platform views in a consistent location of the DOM, as direct children of flt-glass-pane (regardless of the rendering backend: html or canvaskit). Platform views are then "slotted" into the correct position of the App's DOM with standard HTML features.

Up until this change, Flutter web would change the styling of the rendered contents of a platform views to position/size it to the available space. This is no longer the case. Users can now decide how they want to utilize the space allocated to their platform view by the framework.

このため、flt-glass-paneを取得し親要素をチェックすることで、bodyにアクセスすることができます。webのe2eテストでは、そもそもflt-glass-paneにアクセスできないとfailです。

https://github.com/flutter/flutter/blob/2.5.0/dev/integration_tests/web_e2e_tests/lib/common.dart


どうしてもbodyにアクセスしなければならなくなった時に、活用してみてください。

GitHubで編集を提案

Discussion