DEV Community

Cover image for Custom Object Parameter Passing, Page Lifecycle, Custom Popup, Routing to Open Dialog, Network Images
kouwei qing
kouwei qing

Posted on

Custom Object Parameter Passing, Page Lifecycle, Custom Popup, Routing to Open Dialog, Network Images

[Daily HarmonyOS Next Knowledge] Custom Object Parameter Passing, Page Lifecycle, Custom Popup, Routing to Open Dialog, Network Images

1. How to Conveniently Pass Custom Objects as Parameters in HarmonyOS?

Passing Custom Objects as Parameters

In ArkTS syntax, dictionaries have constraints. Using Map requires setting values via set. In ArkTS, object property names cannot be numbers or arbitrary strings (exceptions: string literals or enum string values). Use property names to access class attributes and numeric indices for array elements.

class X {
  public name: string = ''
}
let x: X = { name: 'x' };
console.log(x.name);

let y = ['a', 'b', 'c'];
console.log(y[2]);
Enter fullscreen mode Exit fullscreen mode

For scenarios requiring data access via non-identifier keys (e.g., different key types), use Map<Object, some_type>:

let z = new Map<Object, string>();
z.set('name', '1');
z.set(2, '2');
console.log(z.get('name'));
console.log(z.get(2));

enum Test {
  A = 'aaa',
  B = 'bbb'
}

let obj: Record<string, number> = {
  [Test.A]: 1,   // Enum string values
  [Test.B]: 2,   // Enum string values
  ['value']: 3   // String literals
}
Enter fullscreen mode Exit fullscreen mode

2. In HarmonyOS, besides routes, can we get page-related information? Does the page have a "title" concept?

A UI page consists of one or more custom components. The @Entry-decorated component is the page's entry (root node), and each page has exactly one @Entry. Only @Entry components can call page lifecycle methods, so there is no "title" concept.

Refer to: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-page-custom-components-lifecycle-V5

Relationship between custom components and pages:

  • Custom component: A UI unit decorated with @Component, reusable by combining system components, with component lifecycle callbacks.
  • Page: A UI page composed of one or more custom components. The @Entry-decorated component is the entry (root node), and only it can call page lifecycle methods.

Page lifecycle (for @Entry components):

  • onPageShow: Triggered when the page is displayed (e.g., routing, app foreground).
  • onPageHide: Triggered when the page is hidden (e.g., routing, app background).
  • onBackPress: Triggered when the user clicks the back button.

Component lifecycle (for @Component components):

  • aboutToAppear: Called before the component is rendered, after instance creation.
  • onDidBuild: Called after build() execution, suitable for non-UI operations (e.g., data reporting).
  • aboutToDisappear: Called before component destruction; avoid modifying state variables.

3. Can the style of HarmonyOS popups be customized?

To implement a drop-down popup with full-screen width, set customStyle: true in CustomDialog to maximize the width:

// xxx.ets
import { ResizeDirection } from '@kit.TestKit'

@CustomDialog
struct CustomDialogExampleTwo {
  controllerTwo?: CustomDialogController
  build() {
    Column() {
      Text('我是第二个弹窗')
        .fontSize(30)
        .height(100)
      Button('点我关闭第二个弹窗')
        .onClick(() => {
          if (this.controllerTwo != undefined) {
            this.controllerTwo.close()
          }
        })
        .margin(20)
    }
  }
}
@CustomDialog
struct CustomDialogExample {
  @Link textValue: string
  @Link inputValue: string
  dialogControllerTwo: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExampleTwo(),
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -25 } })
  controller?: CustomDialogController
  cancel: () => void = () => {
  }
  confirm: () => void = () => {
  }

  build() {
    Column() {
      Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
      TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%')
        .onChange((value: string) => {
          this.textValue = value
        })
      Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Button('cancel')
          .onClick(() => {
            if (this.controller != undefined) {
              this.controller.close()
              this.cancel()
            }
          }).backgroundColor(0xffffff).fontColor(Color.Black)
        Button('confirm')
          .onClick(() => {
            if (this.controller != undefined) {
              this.inputValue = this.textValue
              this.controller.close()
              this.confirm()
            }
          }).backgroundColor(0xffffff).fontColor(Color.Red)
      }.margin({ bottom: 10 })

      Button('点我打开第二个弹窗')
        .onClick(() => {
          if (this.dialogControllerTwo != null) {
            this.dialogControllerTwo.open()
          }
        })
        .margin(20)
    }.borderRadius(10).backgroundColor(0x300aff)
  }
}
@Entry
@Component
struct CustomDialogUser {
  @State textValue: string = ''
  @State inputValue: string = 'click me'
  dialogController: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExample({
      cancel: ()=> { this.onCancel() },
      confirm: ()=> { this.onAccept() },
      textValue: $textValue,
      inputValue: $inputValue
    }),
    cancel: this.exitApp,
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: true,
    cornerRadius: 10,
  })

  aboutToDisappear() {
    this.dialogController = null 
  }

  onCancel() {
    console.info('Callback when the first button is clicked')
  }

  onAccept() {
    console.info('Callback when the second button is clicked')
  }

  exitApp() {
    console.info('Click the callback in the blank area')
  }
  build() {
    Column() {
      Button(this.inputValue)
        .onClick(() => {
          if (this.dialogController != null) {
            this.dialogController.open()
          }
        }).backgroundColor(0x317aff)
    }.width('100%').margin({ top: 5 })
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Issues when opening a page via routing in a HarmonyOS CustomDialog

When opening a dialog in Page1 and navigating to Page2 via a button in the dialog, Page2 is inserted between Page1 and the dialog instead of overlaying it.

Refer to: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-navigation-V5

5. How to access online images in HarmonyOS?

The Image component supports online images. Apply for the ohos.permission.INTERNET permission.

Refer to: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/image-V5

Top comments (0)