The Code A is from the Android official compose sample project.
1: I don't understand why author need to assign the varaiable currentScreen for the two times in Code A, and it seems that both Code B and Code C can work well, could you tell me why?
2: In Code A onScreenChange = { screen -> currentScreen = RallyScreen.valueOf(screen) }, where is the paramter screen (It's a sting) assigned?
3: Is Code A a good design? It's hard to understand. If Code C is correct, I think the Code C is easy to see, how about my thinking?
Code A
@Composable
fun RallyApp() {
RallyTheme {
val allScreens = RallyScreen.values().toList()
var currentScreen by rememberSaveable { mutableStateOf(RallyScreen.Overview) }
Scaffold(
topBar = {
RallyTabRow(
allScreens = allScreens,
onTabSelected = { screen -> currentScreen = screen }, //It's One time
currentScreen = currentScreen
)
}
) { innerPadding ->
Box(Modifier.padding(innerPadding)) {
currentScreen.content(
onScreenChange = { screen ->
currentScreen = RallyScreen.valueOf(screen) //It's Two time
}
)
}
}
}
}
enum class RallyScreen(
val icon: ImageVector,
val body: @Composable ((String) -> Unit) -> Unit
) {
Overview(
icon = Icons.Filled.PieChart,
body = { OverviewBody() }
),
Accounts(
icon = Icons.Filled.AttachMoney,
body = { AccountsBody(UserData.accounts) }
),
Bills(
icon = Icons.Filled.MoneyOff,
body = { BillsBody(UserData.bills) }
);
@Composable
fun content(onScreenChange: (String) -> Unit) {
body(onScreenChange)
}
...
}
Code B
@Composable
fun RallyApp() {
RallyTheme {
...
) { innerPadding ->
Box(Modifier.padding(innerPadding)) {
currentScreen.content(
onScreenChange = {null } // I changed
)
}
}
}
}
...//The same as Code A
Code C
@Composable
fun RallyApp() {
RallyTheme {
...
) { innerPadding ->
Box(Modifier.padding(innerPadding)) {
currentScreen.body()
}
}
}
}
enum class RallyScreen(
val icon: ImageVector,
val body: @Composable () -> Unit //I changed
) {
Overview(
icon = Icons.Filled.PieChart,
body = { OverviewBody() }
),
Accounts(
icon = Icons.Filled.AttachMoney,
body = { AccountsBody(UserData.accounts) }
),
Bills(
icon = Icons.Filled.MoneyOff,
body = { BillsBody(UserData.bills) }
);
...
}
from Why need the variable currentScreen to be assigned two times in Android official compose sample project?
No comments:
Post a Comment