Skip to content

Commit fc8856e

Browse files
authored
[web] Don't crash on const HtmlElementView() (flutter#128965)
Previously, when the code contained `const HtmlElementView()` it would break even if it's guarded by `if (kIsWeb)`. This PR makes it such that `const HtmlElementView()` is allowed but it still throws if it gets inserted into the widget tree by mistake on non-web platforms. One improvement we can make in the future is to have a conditional import: - `_html_element_view_web.dart` that contains the real `HtmlElementView` that can only be instantiated on web. - `_html_element_view_io.dart` that contains a stub with an unimplemented `build()` method. Fixes flutter#43532
1 parent 5cb2799 commit fc8856e

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

packages/flutter/lib/src/widgets/platform_view.dart

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ class HtmlElementView extends StatelessWidget {
346346
required this.viewType,
347347
this.onPlatformViewCreated,
348348
this.creationParams,
349-
}) : assert(kIsWeb, 'HtmlElementView is only available on Flutter Web.');
349+
});
350350

351351
/// The unique identifier for the HTML view type to be embedded by this widget.
352352
///
@@ -363,6 +363,7 @@ class HtmlElementView extends StatelessWidget {
363363

364364
@override
365365
Widget build(BuildContext context) {
366+
assert(kIsWeb, 'HtmlElementView is only available on Flutter Web.');
366367
return PlatformViewLink(
367368
viewType: viewType,
368369
onCreatePlatformView: _createHtmlElementView,

packages/flutter/test/widgets/platform_view_test.dart

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3168,4 +3168,28 @@ void main() {
31683168
expect(controller.dispatchedPointerEvents, hasLength(1));
31693169
expect(controller.dispatchedPointerEvents[0], isA<PointerHoverEvent>());
31703170
});
3171+
3172+
testWidgets('HtmlElementView can be instantiated', (WidgetTester tester) async {
3173+
late final Widget htmlElementView;
3174+
expect(() {
3175+
htmlElementView = const HtmlElementView(viewType: 'webview');
3176+
}, returnsNormally);
3177+
3178+
await tester.pumpWidget(
3179+
Center(
3180+
child: SizedBox(
3181+
width: 100,
3182+
height: 100,
3183+
child: htmlElementView,
3184+
),
3185+
)
3186+
);
3187+
await tester.pumpAndSettle();
3188+
3189+
// This file runs on non-web platforms, so we expect `HtmlElementView` to
3190+
// fail.
3191+
final dynamic exception = tester.takeException();
3192+
expect(exception, isAssertionError);
3193+
expect(exception.toString(), contains('HtmlElementView is only available on Flutter Web'));
3194+
});
31713195
}

0 commit comments

Comments
 (0)