I’m working on a Jetpack Compose Multiplatform pro...
# multiplatform
s
I’m working on a Jetpack Compose Multiplatform project for the web, and I need to create a component that adjusts its width dynamically based on the window size. Specifically, I want it to behave like CSS's
min-width
and `max-width`properties, where the width stays between 400 and 450 dp as the window resizes. How can I achieve this with the minimum amount of recomposition?
forgot to mention i also tried
widthIn
modifier but didn't work
s
Could you use Modifier.weight(..) instead and give it a percentage of the width? Or does it need to be strictly defined as between 400 and 450 dp?
s
@Shane Schaefer Yes, it needs to be strictly defined between 400 and 450 dp. Using
Modifier.weight(..)
to assign a percentage of the width might not guarantee the component stays within the specified range.
s
Maybe check out doing custom Intrinsic Measurements for a layout? https://developer.android.com/develop/ui/compose/layouts/intrinsic-measurements
👍 1
s
here is a workaround that i made i made this modifier
Copy code
@Composable
fun Modifier.dynamicWidth(
    min: Dp,
    max: Dp,
    density: Density,
    onWidthChange: (Dp) -> Unit,
) = this.then(
    Modifier.onGloballyPositioned { layoutCoordinates ->
        val parentWidth = with(density) { layoutCoordinates.parentLayoutCoordinates?.size?.width?.toDp() }
        val childWidth = with(density) { layoutCoordinates.size.width.toDp() }
        val result = (parentWidth?.minus(childWidth) ?: 0.dp)
        val newWidth = when {
            result < max && result > min -> result
            result < max && result < min -> min
            else -> max
        }
        onWidthChange(newWidth)
    }
)
After that, I attempted to update an animated state value and passed it as a width. I must admit, though, that this solution isn't ideal because it doesn't rely on the available space within the parent container, but rather on the parent width as a whole.
For instance, in a scenario where I have a row containing several items along with a search bar that utilizes this modifier, the items might become compressed before the parent's width changes. Consequently, the search bar's width will adjust only when the parent's width is altered. but it serves it's purpose that i need for now