[web] Don't crash on const HtmlElementView() (#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 https://github.com/flutter/flutter/issues/43532
This commit is contained in:
@@ -346,7 +346,7 @@ class HtmlElementView extends StatelessWidget {
|
||||
required this.viewType,
|
||||
this.onPlatformViewCreated,
|
||||
this.creationParams,
|
||||
}) : assert(kIsWeb, 'HtmlElementView is only available on Flutter Web.');
|
||||
});
|
||||
|
||||
/// The unique identifier for the HTML view type to be embedded by this widget.
|
||||
///
|
||||
@@ -363,6 +363,7 @@ class HtmlElementView extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
assert(kIsWeb, 'HtmlElementView is only available on Flutter Web.');
|
||||
return PlatformViewLink(
|
||||
viewType: viewType,
|
||||
onCreatePlatformView: _createHtmlElementView,
|
||||
|
||||
@@ -3168,4 +3168,28 @@ void main() {
|
||||
expect(controller.dispatchedPointerEvents, hasLength(1));
|
||||
expect(controller.dispatchedPointerEvents[0], isA<PointerHoverEvent>());
|
||||
});
|
||||
|
||||
testWidgets('HtmlElementView can be instantiated', (WidgetTester tester) async {
|
||||
late final Widget htmlElementView;
|
||||
expect(() {
|
||||
htmlElementView = const HtmlElementView(viewType: 'webview');
|
||||
}, returnsNormally);
|
||||
|
||||
await tester.pumpWidget(
|
||||
Center(
|
||||
child: SizedBox(
|
||||
width: 100,
|
||||
height: 100,
|
||||
child: htmlElementView,
|
||||
),
|
||||
)
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// This file runs on non-web platforms, so we expect `HtmlElementView` to
|
||||
// fail.
|
||||
final dynamic exception = tester.takeException();
|
||||
expect(exception, isAssertionError);
|
||||
expect(exception.toString(), contains('HtmlElementView is only available on Flutter Web'));
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user