DEV Community

HarmonyOS
HarmonyOS

Posted on

Why getParamByName Returns an Array in ArkUI Navigation—and Three Safe Ways to Get a Single Value

Read the original article:Why getParamByName Returns an Array in ArkUI Navigation—and Three Safe Ways to Get a Single Value

Context

When navigating with Navigation, a page pushes another page and passes one parameter. However, the receiver obtains an array instead of a single value.

Description

In ArkUI Navigation, getParamByName(name) returns the parameters for all pages in the back stack that share the same name. If the stack contains multiple NavDestinations named, for example, Page1 (because you pushed Page1 multiple times without clearing older ones), each instance can carry its own parameter. Therefore, getParamByName('Page1') returns an array.

Solution / Approach

You can resolve or avoid the array in three common ways:

A) Accept a specific index from the array (quick fix)

If you know which same-named page instance you need, index into the array.

// Example: pick the 4th Page1 (index 3)
const arg = this.pathStack.getParamByName('Page1')[3] as number;
Enter fullscreen mode Exit fullscreen mode

Pros: simple; Cons: you must be sure about the target index.

B) Ensure only one same-named page exists (singleton)

Keep only a single Page1 in the stack—then getParamByName('Page1') returns a single-element array.

  1. Use LaunchMode singleton so only one instance can exist: Docs
    Use MOVE_TO_TOP_SINGLETON or POP_TO_SINGLETON.

  2. Manually remove duplicates before pushing a new one: Docs

// Remove existing Page1(s) first, then push
this.pathStack.removeByName('Page1');
this.pathStack.pushPath({ name: 'Page1', param: 42 });
Enter fullscreen mode Exit fullscreen mode

C) Use getParamByIndex (index is unique)

If you know the target’s stack index, fetch by index—this returns a single value, not an array. Docs

// Example: get param of the top page
const topIndex = this.pathStack.size() - 1;
const arg = this.pathStack.getParamByIndex(topIndex) as number;
Enter fullscreen mode Exit fullscreen mode

Pros: deterministic; Cons: you must know (or compute) the index.

Key Takeaways

  • getParamByName(name) aggregates all same-named pages’ params → array.
  • Use singleton launch modes or remove duplicates to keep one instance.
  • Or switch to getParamByIndex for a single, index-specific result.

Additional Resources

Written by Bunyamin Eymen Alagoz

Top comments (0)