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?

Jetpack Composeの引数パラメーターにロジックが含まれている場合、専用のクラスにまとめる

Last updated at Posted at 2025-09-19

はじめに

自分の備忘録として記録

概要

ロジックがComposeの引数に含まれた場合、専用のクラスに閉じ込める。(以下のgoodButtonColors)
これにより可読性の向上が見込める。

bad

bad.kt
@Composable
fun Button(
    onClick: () -> Unit,
    enabled: Boolean = true,
    backgroundColor =
        if (enabled) ButtonDefaults.enabledBackgroundColor
        else ButtonDefaults.disabledBackgroundColor,
    content: @Composable RowScope.() -> Unit
) {}

good

good.kt
@Composable
fun Button(
    onClick: () -> Unit,
    enabled: Boolean = true,
    colors: ButtonColors = ButtonDefaults.colors(),
) {
    val backgroundColor = colors.backgroundColor(enabled)
}

class ButtonColors(
    backgroundColor: Color,
    disabledBackgroundColor: Color,
    contentColor: Color,
    disabledContentColor: Color
) {
    fun backgroundColor(enabled: Boolean): Color {
        // class内部で条件分岐
        return if (enabled) backgroundColor else disabledBackgroundColor
    }
}

object ButtonDefaults {
    fun colors(
        backgroundColor: Color = ...,
        disabledBackgroundColor: Color = ...,
        disabledContentColor: Color = ...
    ): ButtonColors { ... }
}

おわりに

UIKit, StoryBoardを利用したiOS開発をしてきた自分にとっては、FlutterやComposeの宣言的UIの経験が少ない。
簡単な内容ではあるが、tipsとして記録

参考リンク

DroidKaigi 2025 - [JA] これでもう迷わない!Jetpack Composeの書き方実践ガイド | b4tchkn

API Guidelines for @Composable components in Jetpack Compose - ComponentColor/ComponentElevation objects

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?