android-templates
android-templates copied to clipboard
Define BaseScreen composable for all screens
Why
The composable screens in the Compose Template do not yet have a base screen component. So, it's hard to manage a logic that should be implemented from all screens. We can implement that logic on each screen. However, this approach easily leads to missing or inconsistent implementations.
For example, we want to switch the status bar color between light & dark between screens. Implementing the call to request dark or light status bar on each screen works.
val systemUiController = rememberSystemUiController()
systemUiController.setStatusBarColor(
color = Transparent,
darkIcons = false/true,
)
However, having a logic from a base screen component to force requests on all screens makes more sense.
Solution
Create a BaseScreen
composable for all screens, as we did with BaseActivity
or BaseFragment
. This BaseScreen will contain base parameters to request & base logic in the body to execute for all screens.
For example,
@Composable
fun BaseScreen(
isDarkStatusBarIcons: Boolean? = null,
content: @Composable () -> Unit,
) {
if (isDarkStatusBarIcons != null) {
setStatusBarColor(darkIcons = isDarkStatusBarIcons)
}
content()
}
@Composable
fun HomeScreen(
navigator: (destination: AppDestination) -> Unit,
viewModel: HomeViewModel = hiltViewModel(),
) = BaseScreen(
isDarkStatusBarIcons = false
) {
HomeScreenContent(...)
}
@Composable
fun setStatusBarColor(darkIcons: Boolean) {
val systemUiController = rememberSystemUiController()
LaunchedEffect(key1 = darkIcons) {
systemUiController.setStatusBarColor(
color = Transparent,
darkIcons = darkIcons,
)
}
}
Who Benefits?
Developers