Home > Back-end >  How to create custom rememberState in jetpack compose?
How to create custom rememberState in jetpack compose?

Time:08-17

Can we create out own custom rememberState like rememberModalButtomSheetSTate(). Also I want to store composable inside this rememberState and able to set and access composable using this state. Like rememberState.setCompose = @Composable and rememberState.getComposable

CodePudding user response:

Yes, you can create rememberable functions such as rememberModalBottomSheetState or rememberLazyListState. Creating custom remember functions that store multiple data type or MutableStates are common. Putting Composables is not common, at least i haven't seen so far, but it's doable.

class MyState internal constructor() {
   var state1 by mutableStateOf(0)
   var state2 by mutableStateOf(0)
   var someValue = 0
}

internal constructor is optional, it's for restricting developer to create instance only by remember function.

// you can add params to pass to MyState instance or keys to reset remember
@Composable
fun rememberMyState(key1: Any?): MyState {
    return remember(key1) {
        MyState()
    }
}

If you wish to add Composables one way of doing it is

class MyState internal constructor() {
    var state1 by mutableStateOf(0)
    var state2 by mutableStateOf(0)
    var someValue = 0
    // this can also be SnapshoStateList to trigger recomposition when you add, remove or update list with new item instance
    val list = mutableListOf<@Composable () -> Unit>()
}

Usage

val myState = rememberMyState(key1 = Unit)
myState.list.add {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(100.dp)
            .background(Color.Red)
    )
}

myState.list.add {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(100.dp)
            .background(Color.Yellow)
    )
}

Column(modifier = Modifier.fillMaxSize()) {
    myState.list.forEach{
        it.invoke()
    }
}
  • Related