https://kotlinlang.org logo
#compose
Title
# compose
o

Olivier Patry

03/01/2021, 5:56 PM
If I want to display a master/detail on tablet with Jetpack Compose, do you have some guidelines? For now, I went to something like:
Copy code
@Composable
fun MainLayout(catRepository: CatRepository = (CatRepository((FakeCatDataSource())))) {
    val catsViewModel = viewModel<CatsViewModel>(factory = CatsViewModelFactory(catRepository))
    Surface(color = MaterialTheme.colors.background) {
        when {
            !booleanResource(R.bool.is_tablet) -> MainLayoutTabletPhone(catsViewModel)
            booleanResource(R.bool.is_portrait) -> MainLayoutTabletPortrait(catsViewModel)
            else -> MainLayoutTabletLandscape(catsViewModel)
        }
    }
}
In the Phone version, I use a nav controller to move from list to detail. In the Tablet version(s), I use a
var selected by remmeber { mutableStateOf<MyModel>(null) }
I don't know if there is better nor if there are cons against this.
Also, how would you deal with configuration change and the
mutableState
(currently stored in each individual composable), would you hoist it?
I tried extracting
Copy code
var selectedCat by remember { mutableStateOf<CatModel?>(null) }
on parent
@Composable
and giving the selected state and the selection callback, it works but configuration change doesn't restore the state
using
rememberSaveable
seems to solve, is it the recommended solution?
So, here is my current working solution, don't know if it's a good/recommended way to achieve master/detail on both Phone & Tablet
Copy code
if (booleanResource(R.bool.is_tablet)) {
    var selectedCatUUID by rememberSaveable { mutableStateOf<UUID?>(null) }
    val selectedCat = selectedCatUUID?.let { uuid ->
        catsViewModel.findCatByUUID(uuid)
    }
    if (booleanResource(R.bool.is_portrait)) {
        MainLayoutTabletPortrait(catsViewModel, selectedCat) { cat ->
            selectedCatUUID = cat.uuid
        }
    } else {
        MainLayoutTabletLandscape(catsViewModel, selectedCat) { cat ->
            selectedCatUUID = cat.uuid
        }
    }
} else {
    MainLayoutTabletPhone(catsViewModel)
}
6 Views