Issue
I want to apply modifier in such a way that if the width is provided, it should use the provided width, else use the max-width available.
I am applying the Modifier in the below fashion, but the result is not as expected. The view width is going haywire. Requesting guidance here.
val myModifier = Modifier.padding(
start = 4.dp, end = 4.dp, top = 8.dp, bottom = 8.dp
)
if (viewWidth == null)
myModifier.then(Modifier.fillParentMaxWidth(1f))
else
myModifier.then(Modifier.width(viewWidth))
myModifier.then(
Modifier.height(viewHeight ?: 100.dp)
.clickable(onClick = { listener.onItemClick(item) })
)
Solution
Modifier
has a then
function to concatenate the current modifier with another modifier. This then
function returns a new modifier that you have not used it. You have to re-initialize your myModifier
variable with the returned modifier.
Check the below code:
var myModifier = Modifier.padding(
start = 4.dp, end = 4.dp, top = 8.dp, bottom = 8.dp
)
if (viewWidth == null)
myModifier = myModifier.then(Modifier.fillParentMaxWidth(1f))
else
myModifier = myModifier.then(Modifier.width(viewWidth))
myModifier = myModifier.then(
Modifier
.height(viewHeight ?: 100.dp)
.clickable(onClick = { listener.onItemClick(item) })
)
Answered By - Avijit Karmakar
Answer Checked By - Clifford M. (JavaFixing Volunteer)