Home > Net >  Scope composables to a parent composable
Scope composables to a parent composable

Time:10-03

I'm making an implementation of PreferencesScreen in Compose and I've made all the components like PreferencesSwitch, CheckBox, etc.
Now I'm wondering if there is any way to make it so all the components can only be used inside the scope of the PreferencesScreen function and cannot be used outside of it.
Like for example, in LazyColumn, items can only be used inside LazyColumnScope. I looked at the implementation of it but it used the annotation @LazyScopeMarker so I'm assuming there's different markers for different scopes?

Expected Behaviour:

PreferencesScreen{
    PreferencesCheckBox(...){ ... }
}

is possible but,

PreferencesCheckBox(...){ ... }

alone is not possible.

CodePudding user response:

You can declare some scope same like LazyColumn does:

interface PreferencesScreenScope {
    @Composable
    fun PreferencesCheckBox()
}

private class PreferencesScreenScopeImpl: PreferencesScreenScope {
    @Composable
    override fun PreferencesCheckBox() {

    }
}

interface/class ...Impl is used here to make sure that no other screen can reuse PreferencesScreenScopeImpl, also it adds testing possibility.

Use it in PreferencesScreen:

@Composable
fun PreferencesScreen(content: @Composable PreferencesScreenScope.() -> Unit ) {
    PreferencesScreenScopeImpl().content()
}

Use PreferencesScreen like this:

PreferencesScreen {
    PreferencesCheckBox()
}
  • Related