• Mouad Debbar's avatar
    [web] Pass creation params to the platform view factory (#128146) · b0188cd1
    Mouad Debbar authored
    This concludes step 1 of the `HtmlElementView` improvements. It's now possible to pass creation params to platform view factories directly from `HtmlElementView`.
    
    Here's a sample app using a single factory to render platform views in different colors:
    
    <details>
      <summary>Code sample</summary>
      
      ```dart
    import 'dart:js_interop';
    import 'dart:ui_web' as ui_web;
    import 'package:flutter/material.dart';
    import 'package:web/web.dart' as web;
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Platform View Demo',
          home: Scaffold(
            appBar: AppBar(
              title: Text('Platform View Demo'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  BoxWrapper('red'),
                  BoxWrapper(null),
                  BoxWrapper('blue'),
                ],
              ),
            ),
          ),
        );
      }
    }
    
    bool isRegistered = false;
    
    class BoxWrapper extends StatelessWidget {
      const BoxWrapper(this.cssColor);
    
      final String? cssColor;
    
      void register() {
        if (isRegistered) return;
        isRegistered = true;
    
        ui_web.platformViewRegistry.registerViewFactory('my-platform-view', (
          id, {
          Object? params,
        }) {
          params as String?;
    
          final element = web.document.createElement('div'.toJS) as web.HTMLElement;
          element.textContent = 'Platform View'.toJS;
          element.style
            ..lineHeight = '100px'.toJS
            ..fontSize = '24px'.toJS
            ..backgroundColor = (params ?? 'pink').toJS
            ..textAlign = 'center'.toJS;
          return element;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        register();
        return SizedBox(
          width: 200,
          height: 100,
          child: Card(
            child: HtmlElementView(
              viewType: 'my-platform-view',
              creationParams: cssColor,
            ),
          ),
        );
      }
    }
      ```
    </details>
    
    ![image](https://github.com/flutter/flutter/assets/1278212/4b62ed8b-2314-49d6-9b4a-5da849bf2a48)
    
    Depends on https://github.com/flutter/engine/pull/42255
    
    Part of https://github.com/flutter/flutter/issues/127030
    b0188cd1
html_element_view_test.dart 8.41 KB