目录

Dynamic Component Creation

Overview

To solve the problem of slow page and component loading, the ArkUI framework provides dynamic operations to pre-create components and allows apps to load and render components as required during runtime. Dynamic operations include dynamically creating (or adding) components and dynamically uninstalling (or deleting) components. Dynamically creating a component refers to creating a component in a non-build lifecycle, that is, creating a component before the build lifecycle. In this way, you can save the component creation time and improve user experience. In addition, you can encapsulate independent logic to facilitate modular development of apps. Dynamically uninstalling a component is to uninstall or delete a dynamically created component.

Component Pre-Creation Principle

In the declarative paradigm, components are created only in the build phase. You cannot create components in other lifecycle phases. As a result, page loading is slow. Different from the declarative paradigm, the dynamic UI operations provided by the ArkUI framework support component pre-creation. Component pre-creation allows you to create components in the non-build lifecycle. After a component is created, you can set attributes and calculate the layout of the component. Then, the component can be used during page loading to greatly improve the page response speed.

As shown in the following figure, the component pre-creation mechanism can be used to pre-create components and set attributes during the idle time of the animation execution process. After the animation ends, the attribute and the layout are updated, so that the time for creating the component is saved, and page rendering is accelerated.

Advantages of Custom FrameNodes in Dynamic Layout Scenarios

[h2]Reducing Custom Component Creation Overhead

In declarative development paradigm, if you use the custom component of ArkUI to define each node in the node tree, the node creation efficiency is low.

This is mainly because each node needs to allocate memory in the ArkTS engine to store custom components and state variables of the app. In addition, during node creation, you must collect component IDs, component closures, and dependencies between state variables.

In contrast, using the custom component node (FrameNode) of ArkUI can avoid creating custom component objects and state variable objects, and eliminate the need for dependency collection, significantly improving the component creation speed.

[h2]Faster Component Update

In the update of the dynamic layout class framework, there is usually a UI component tree TreeA created by a tree data structure ViewModelA. Although the declarative development paradigm can implement data-driven automatic update, there are a large number of diff operations when you use the new data structure ViewModelB to update TreeA, as shown in the following figure. When the diff algorithm is executed on a complex component tree (with a depth of more than 30 layers and including 100 to 200 components), the ArkTS engine is hardly able to keep a full frame at 120 Hz refresh rate. However, with the FrameNode extension of ArkUI, the framework can independently control the update process and achieve efficient on-demand pruning. Especially for dynamic layout frameworks that are only used for a few specific services, utilizing this extension can achieve extremely rapid update operations.

[h2]Directly Operating the Component Tree

The declarative development paradigm falls short in updating the component tree structure. For example, if a subtree in the component tree is completely moved from the current child node to another child node, the declarative development paradigm cannot be used to directly adjust the structure relationship of the component instance. The preceding operations can be implemented only by re-rendering the entire component tree. If the FrameNode extension of ArkUI is used, the subtree can be easily controlled and ported to another node. In this way, only partial rendering and refreshing are performed, resulting in better performance.

Dynamically Adding, Updating, and Deleting Components

[h2]Dynamically Adding Components

To dynamically add a component, perform the following steps:

  1. Create a custom node.
  2. The NodeController class is used to manage operations such as creating, displaying, and updating custom nodes, and mounts custom nodes to the NodeContainer.
  3. Implement the makeNode() method of the NodeController. The makeNode() method is called back when the NodeController instance is bound to the NodeContainer and mounts the returned node to the NodeContainer.
  4. Use NodeContainer to display custom nodes.

[h2]Dynamically Deleting Components

You can use condition control statements to remove or display a NodeContainer node. In the example code, if this.isShow is changed to false, the node is removed from the GUI.

// ...
@Entry
@Component
struct Index {
  @State message: string = "hello";
  @State isShow: boolean = true;
  private textNodeController: TextNodeController = new TextNodeController(this.message);

  build() {
    Row() {
      Column() {
        if (this.isShow) {
          NodeContainer(this.textNodeController)
            .width('100%')
            .height(100)
            .backgroundColor('#FFF0F0F0')
        }
        Button('isShow')
          .onClick(() => {
            this.isShow = false;
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

[h2]Dynamically Updating Components

You can use the makeNode() and rebuild() methods of NodeController to dynamically replace nodes in NodeContainer. The rebuild method triggers the makeNode callback to refresh the nodes displayed in the NodeContainer. If the return value of the makeNode() method is null, the nodes mounted to the NodeContainer are removed.

// ...

class TextNodeController extends NodeController {
  private textNode: BuilderNode<[Params]> | null = null;
  private message: string = '';

  constructor(message: string) {
    super();
    this.message = message;
  }

  makeNode(context: UIContext): FrameNode | null {
    if (this.textNode == null) {
      this.textNode = new BuilderNode(context);
      this.textNode.build(wrapBuilder<[Params]>(testBuilder), new Params(this.message));
    }

    return this.textNode.getFrameNode();
  }

  replaceBuilderNode(newNode: BuilderNode<Object[]>) {
    this.textNode = newNode;
    this.rebuild();
  }
}

// ...

You can create a node based on the site requirements. The sample code is as follows:

// ...
@Entry
@Component
struct Index {
  @State message: string = "hello";
  @State isShow: boolean = true;
  private textNodeController: TextNodeController = new TextNodeController(this.message);
  // private count = 0;

  build() {
    Row() {
      Column() {
        if (this.isShow) {
          NodeContainer(this.textNodeController)
            .width('100%')
            .height(100)
            .backgroundColor('#FFF0F0F0')
        }
        Button('replaceNode')
          .onClick(() => {
            this.textNodeController.replaceBuilderNode(this.buildNewNode());
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }

  buildNewNode(): BuilderNode<[Params]> {
    let uiContext: UIContext = this.getUIContext();
    let message = 'newNode';
    let textNode = new BuilderNode<[Params]>(uiContext);
    textNode.build(wrapBuilder<[Params]>(testBuilder), new Params(message))
    return textNode;
  }
}

[h2]NodeController Lifecycle

NodeController is used to control and feed back the behavior of the node on the corresponding NodeContainer. This function must be used together with NodeContainer. The following describes the common lifecycle functions:

 export abstract class NodeController {
   abstract makeNode(uiContext: UIContext): FrameNode | null;
   aboutToResize?(size: Size): void;
   aboutToAppear?(): void;
   aboutToDisappear?(): void;
   abstract rebuild(): void;
   onTouchEvent?(event: TouchEvent): void;
 }

Practice Cases of List-Stream Ad Components

[h2]Scenario

In app advertising, there is a scenario known as list-stream advertising, where ad entries are interspersed within the app's list views, such as news feeds or product listings. The goal is to seamlessly integrate ads into the user's browsing experience, making them appear as regular content items (though ad entries need to be marked to distinguish them from non-ad content), thereby attracting users' attention and increasing engagement.

The layout and content of these ads are usually not determined at the development stage (they could be in the form of images and text, videos, or other formats). During runtime, the ads rely on data sent from the server for logic mapping. This data is then used to construct the layout and load or display the ad content. To ensure seamless integration of list-stream ads, the app must utilize the capability of dynamically creating components.

[h2]Solution

  1. Construct a list layout with list data and implement logic based on the data type. For the ad type, use NodeContainer to reserve a placeholder.
  2. Initiate a request to obtain data such as ad information during NodeContainer rendering. Parse the obtained data to identify the ad type, and then construct the type-specific layout, such as an image-text layout or a video layout.
  3. After the layout construction, return rootNode to mount the component onto the tree, and then render and display it in the container.

[h2]Development Procedure

  1. Load list data: Simulate the process of obtaining list data from the server and generating a list data object and an ad data object.

    aboutToAppear() {
      for (let i = 0; i <= 100; i++) {
        let id = i.toString();
        if (i % 7 === 6) {
          this.data.pushData(new CardData(true, id));
          try {
            this.idList.add(id);
          } catch (error) {
            let err = error as BusinessError
            if (err.code) {
              hilog.error(0x0000, 'ImperativeView', 'Failed to add id. Cause: %{public}s', JSON.stringify(err) ?? '');
            }
          }
        } else {
          this.data.pushData(new CardData(false, id));
        }
      }
    }

    In the sample code, CardData(true, id) indicates the ad data object.

    export class CardData {
      private id: string = '';
      private mIsAdCard: boolean = false;
    
      constructor(isAdCard: boolean, id: string) {
        this.mIsAdCard = isAdCard;
        this.id = id;
      }
      // ...
    }
  2. Build an ad component: Encapsulate the ad component AdComponent. It determines whether to build a text and image or a video ad component based on the ad type obtained through simulation.

    @Builder
    export function adBuilder(param: AdParams) {
      AdComponent({ params: param });
    }
    
    @Component
    struct AdComponent {
      params ?: AdParams;
      closeAdDialogController: CustomDialogController = new CustomDialogController({
        builder: CloseAdDialog({
          adId: this.params!.id
        }),
        backgroundBlurStyle: BlurStyle.COMPONENT_THICK,
      });
    
      build() {
        if (this.params!.isVideo) {
          videoAdBuilder(this.closeAdDialogController);
        } else {
          picAdBuilder(this.closeAdDialogController);
        }
      }
    }
  3. Implement the ad placeholder node logic: Implement the placeholder node AdNodeController, which is inherited from NodeController. The initAd() method adds the ad component to the rootNode through the this.adNode.build() API. When the NodeContainer is rendered, it calls the makeNode() method, which returns the constructed rootNode to facilitate mounting the component into the component tree.

    export class AdNodeController extends NodeController {
      private rootNode: FrameNode | null = null;
      private adNode: BuilderNode<[AdParams]> | null = null;
      private isRemove: boolean = false;
      private uiContext ?: UIContext;
    
      makeNode(): FrameNode | null {
        if (this.isRemove) {
          return null;
        }
        if (this.rootNode != null) {
          return this.rootNode;
        }
        return null;
      }
    
      initAd(uiContext: UIContext, id: string, adType: string) {
        this.uiContext = uiContext;
        this.rootNode = new FrameNode(this.uiContext);
        this.adNode = new BuilderNode(this.uiContext);
        this.adNode.build(wrapBuilder(adBuilder), { id: id, isVideo: adType === 'video' });
        this.rootNode.getRenderNode()?.appendChild(this.adNode.getFrameNode()?.getRenderNode());
      }
    
      remove() {
        this.isRemove = true;
      }
    }
  4. Load the ad layout: The getAdNodeController() method is used to simulate the obtaining of ad type information through queryAdById(). After the information is obtained, the corresponding NodeController is constructed.

    export const getAdNodeController = (uiContext: UIContext, id: string): AdNodeController | undefined => {
      let baseNode = new AdNodeController();
      nodeMap.set(id, baseNode);
      baseNode.initAd(uiContext, id, queryAdById(id));
      return nodeMap.get(id);
    }
    
    function queryAdById(id: string): string {
      if (Number(id) % 2 === 0) {
        return 'pic';
      } else {
        return 'video';
      }
    }
  5. Lay out list items, including ad items: In the ListItem layout logic, it is necessary to check whether the item is an ad node. If yes, embed a NodeContainer as the placeholder via getAdNodeController(). If not, use CardComponent() to lay out and render the list items.

    List({ space: 3 }) {
      LazyForEach(this.data, (item: CardData) => {
        ListItem() {
          if (item.isAdCard()) {
            NodeContainer(getAdNodeController(this.getUIContext(), item.getId())).width($r('app.string.percent_100'));
          } else {
            CardComponent({ cardData: item });
          }
        }
        .margin({
          left: $r('app.string.spacing_xxl'),
          right: $r('app.string.spacing_xxl')
        })
      }, (item: CardData) => item.getId())
    }
    .width($r('app.string.percent_100'))
    .height($r('app.string.percent_100'))
    .cachedCount(5)
  6. Implement the ad component close/block functionality: The ad component needs to provide a close function. When the user clicks the confirm block button, the node.remove() method is called to notify the AdNodeController to mark the ad as removed by setting this.isRemove to true. Then, the node.rebuild() API is called to trigger a component re-rendering. At this point, the system will execute the makeNode API again, and based on the this.isRemove flag, it will return a null node, effectively removing the ad component from the component tree.

    Button($r('app.string.text_dialog_shield'))
      .onClick(() => {
        let node: AdNodeController | undefined = nodeMap.get(this.adId);
        if (node !== undefined) {
          node.remove();
          node.rebuild();
        }
        this.dialogController.close();
      })

Cases of Dynamically Generating Pages

[h2]Scenario

The following describes how to use the FrameNode of ArkUI to implement dynamic layout in the scenario where the image resources are refreshed on the video home page.

[h2]Declarative Extension of ArkUI

The DSL of a simplified dynamic layout framework generally uses data exchange formats such as JSON and XML to describe the UI. The following uses JSON as an example. The following table describes the core fields in this case.

Tag Description
type Type of a UI component, which usually corresponds to a native component or an encapsulated component.
content Content of the text and image components.
css Layout features of UI components.
children Child component of the current component.
  1. Define the UI description data of the video app home page. Create the structure.json file in the resources/rawfile directory. The sample code is as follows:

    {
      "type": "Column",
      "css": {
        "width": "100%"
      },
      "children": [
        // ...
      ]
    }
  2. Define the corresponding data structure to receive UI description data. The sample code is as follows:

    class VM {
      type?: string;
      content?: string;
      css?: ESObject;
      children?: VM[];
      id?: string;
    }
  3. Customize the DSL parsing logic and use carouselNodes to save the carousel image nodes to facilitate subsequent updates. The sample code is as follows:

    let carouselNodes: typeNode.Image[] = [];
    
    function FrameNodeFactory(vm: VM, context: UIContext): FrameNode | null {
      if (vm.type === "Column") {
        let node = typeNode.createNode(context, "Column");
        setColumnNodeAttr(node, vm.css);
        vm.children?.forEach(kid => {
          let child = FrameNodeFactory(kid, context);
          node.appendChild(child);
        });
        return node;
      } else if (vm.type === "Row") {
        // ...
      } else if (vm.type === "Swiper") {
        // ...
      } else if (vm.type === "Image") {
        // ...
      } else if (vm.type === "Text") {
        // ...
      }
      return null;
    }
    
    function setColumnNodeAttr(node: typeNode.Column, css: ESObject) {
      node.attribute.width(css.width);
      node.attribute.height(css.height);
      node.attribute.backgroundColor(css.backgroundColor);
      node.attribute.justifyContent(FlexAlign.End);
    
        if (css.alignItems === "HorizontalAlign.Start") {
        node.attribute.alignItems(HorizontalAlign.Start);
      }
      if (css.padding !== undefined) {
        node.attribute.padding(css.padding as Padding);
      }
      if (css.margin !== undefined) {
        node.attribute.margin(css.margin as Padding);
      }
    }
    
    function setRowNodeAttr(node: typeNode.Row, css: ESObject) {
      node.attribute.width(css.width);
      node.attribute.height(css.height);
      if (css.padding !== undefined) {
        node.attribute.padding(css.padding as Padding);
      }
      if (css.margin !== undefined) {
        node.attribute.margin(css.margin as Padding);
      }
      node.attribute.justifyContent(FlexAlign.SpaceBetween);
    }
  4. Use the NodeContainer component to nest the FrameNode extension of ArkUI and the declarative syntax of ArkUI. The sample code is as follows:

    class ImperativeController extends NodeController {
      // ...
      makeNode(uiContext: UIContext): FrameNode | null {
        return frameNodeFactory(data, uiContext);
      }
    }
    
    @Component
    export struct ImperativePage {
      private controller: ImperativeController = new ImperativeController();
    
      build() {
        Column() {
          NodeContainer(this.controller)
        }
        .height('100%')
        .width('100%')
        .backgroundColor(Color.Black)
      }
    }

[h2]Performance Comparison

The following uses two solutions in the scenario sample to describe how to use the Profile tool of DevEco Studio to capture traces for performance analysis and comparison.

  1. The following figure shows that the completion latency in the declarative development paradigm is 13.7 ms. (The data varies depending on the device and scenario. For reference only.)

  2. The following figure shows that the completion latency in FrameNode extension mode is 6.1 ms. (The data varies depending on the device and scenario. For reference only.)

Sample Code