2

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) {
       ...
    }
  }
}
Johan Paul
  • 2,203
  • 2
  • 22
  • 38
  • Another way of looking at this would be to ask; how can I make new modifiers that are only interested in some specific values of the passed in Modifier? Say the passed in Modifier has .background(..).size(40.dp) and I want to only pass in the size value from this Modifier down to the child. – Johan Paul Sep 23 '21 at 06:50
  • 2
    No can do : https://stackoverflow.com/q/68725596/15880865 – Richard Onslow Roper Sep 23 '21 at 07:22

1 Answers1

4

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.

Evolitist
  • 56
  • 2
  • Thanks! Good to know that the Compose team has considered this case also and some support is on its way! I think this is necessary in some custom drawing cases, where we need more control over exact sizes. – Johan Paul Sep 23 '21 at 08:04