Cannot use MenuItemColors.copy()

48 Views Asked by At

The docs for material3 MenuItemColors refers to a public copy() method, but in AS I get "unresolved reference", and there is no extension function to import:

import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.MenuItemColors

@Composable 
fun CantCopyColors () {
    val mic = MenuDefaults.itemColors() // Returns MenuItemColors
    val copy = mic.copy()
                // ^^^^ Error
}

This happens with a newly constructed object as well as the itemColors() default (ie., calling .copy() on the object it returns, as above, and not using parameters to itemColors() instead).

Happens in both AS Hedgehog 2032.1.1 and JellyFish 2023.3.1 (Canary 4) using material3 1.2.0-beta01 (beta02 gives me some insurmountable IncompatibleClassChangeErrors).

Is this a just plain bug or is there something I don't understand?

1

There are 1 best solutions below

3
BenjyTec On BEST ANSWER

By looking at the source code it seems like the copy function should be present. I don't know why it does not appear to work, but from the source code, it seems like you can also pass your wished overrides of colors directly to the itemColors() function.

@Composable
fun itemColors(
    textColor: Color = Color.Unspecified,
    leadingIconColor: Color = Color.Unspecified,
    trailingIconColor: Color = Color.Unspecified,
    disabledTextColor: Color = Color.Unspecified,
    disabledLeadingIconColor: Color = Color.Unspecified,
    disabledTrailingIconColor: Color = Color.Unspecified,
): MenuItemColors = MaterialTheme.colorScheme.defaultMenuItemColors.copy(
    textColor = textColor,
    leadingIconColor = leadingIconColor,
    trailingIconColor = trailingIconColor,
    disabledTextColor = disabledTextColor,
    disabledLeadingIconColor = disabledLeadingIconColor,
    disabledTrailingIconColor = disabledTrailingIconColor,
)

So instead of

val mic = MenuDefaults.itemColors() // Returns MenuItemColors
val copy = mic.copy(textColor = Color.Red)

try to do it as follows:

val mic = MenuDefaults.itemColors(textColor = Color.Red)

Please consider to open a ticket on the Google Issue Tracker about this strange case and link the issue here.