0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Navigation3を用いたスタック管理と遷移処理まとめ

0
Posted at

はじめに

今まで何種類かNavigation3の実装例を書いてきましたが、スタック管理と遷移処理のまとめ記事を書いてみようと思います

コード

/**
 * 特定のキーまでバックスタックを削除して遷移
 * @param destination 遷移先のキー
 * @param popUpTo どのキーまで戻るか(nullの場合はスタックをクリア)
 * @param inclusive trueの場合、popUpToで指定したキーも削除
 */
fun NavBackStack.navigateAndClearBackStack(
    destination: NavKey,
    popUpTo: NavKey? = null,
    inclusive: Boolean = false
) {
    if (popUpTo != null) {
        // 特定のキーまで戻る
        val targetIndex = indexOfLast { it == popUpTo }
        if (targetIndex >= 0) {
            val removeFrom = if (inclusive) targetIndex else targetIndex + 1
            while (size > removeFrom) {
                removeLast()
            }
        }
    } else {
        // スタック全体をクリア
        while (size > 1) {
            removeLast()
        }
        if (lastOrNull() != destination) {
            removeLast()
        }
    }

    // 遷移先を追加(既に存在しない場合のみ)
    if (lastOrNull() != destination) {
        add(destination)
    }
}

/**
 * スタック全体をクリアして新しいルートに置き換え
 */
fun NavBackStack.replaceAll(destination: NavKey) {
    clear()
    add(destination)
}

/**
 * 特定のキーを削除(存在する場合)
 */
fun NavBackStack.removeKey(key: NavKey) {
    val index = indexOf(key)
    if (index >= 0) {
        removeAt(index)
    }
}

最後に

直感的に操作しやすくて助かりますよね
早く実践でもっと使いたいものですね

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?