Modifiers depending on other modifier's values in Jetpack Compose?

Viewed 748

How can I create new Modifiers that depend on some other Modifiers' values? Say, for the sake of an example, I want to make the child components's height to be half of the one that is passed in from the parent plus some constant (thus not being able to use fillMaxHeight(fraction: Float)).

@Composable
fun View() {
   MyComposable(modifier = Modifier.size(40.dp))
}

@Composable
fun MyComposable(
  modifier: Modifier          // Assuming this modifier contains a size
) {
  Box(modifier) {             // Setting the the size from the passed in modifier
    val childHeightModifier = Modifier.height(???) // <-- Wanted to be some specific value depending on parent size
    
    Box(childHeightModifier) {
       ...
    }
  }
}
1 Answers

You can use BoxWithConstraints for this particular usecase, it provides constraints imposed by parent to its children:

@Composable
fun View() {
   MyComposable(modifier = Modifier.size(40.dp))
}

@Composable
fun MyComposable(modifier: Modifier) {
  BoxWithConstraints(modifier) { // this: BoxWithConstraintsScope
    val childHeightModifier = Modifier.height(maxHeight * 0.5f)
    Box(childHeightModifier) {
       ...
    }
  }
}

As for communication between Modifiers, there's a ModifierLocal system in the works, which will allow doing exactly that.

Related