Estado en Jetpack Compose

Qué es el estado en JetpackCompose

Estado en Compose

Ejemplo: Crear una aplicación que sume 2 números

Crear un nuevo proyecto llamado Estado

Añadir la dependencia de material en el fichero build.gradle:

implementation("androidx.compose.material:material:1.5.4")

Añadir el fichero Components.kt para crear un TextField modificado

@Composable
fun OperandTextField(
    label: String,
    number: String,
    numberChange: (String) -> Unit
) {
    TextField(
        value = number,
        onValueChange = numberChange,
        label = { Text(label) },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
    )
}

@Composable
fun Spacer() {
    androidx.compose.foundation.layout.Spacer(modifier = Modifier.size(16.dp))
}

Añadir el fichero StatelessComposable.kt

@Composable
@Preview
fun SumScreen() {
    var firstNumber by remember { mutableStateOf("1") }
    var secondNumber by remember { mutableStateOf("2") }
    var sum by remember { mutableStateOf(3.0) }

    SumContent(
        firstNumber,
        secondNumber,
        firstNumberChange = { firstNumber = it },
        secondNumberChange = { secondNumber = it },
        sum,
        onCalculate = { sum = firstNumber.toDoubleOrZero() + secondNumber.toDoubleOrZero() }
    )
}

@Composable
private fun SumContent(
    firstNumber: String,
    secondNumber: String,
    firstNumberChange: (String) -> Unit,
    secondNumberChange: (String) -> Unit,
    sum: Double,
    onCalculate: () -> Unit
) {

    Column(
        Modifier
            .fillMaxSize()
            .padding(vertical = 64.dp, horizontal = 16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        OperandTextField(
            label = "Número 1",
            number = firstNumber,
            numberChange = firstNumberChange
        )

        Spacer()

        OperandTextField(
            label = "Número 2",
            number = secondNumber,
            numberChange = secondNumberChange
        )

        Spacer()

        Text(
            text = "Suma = $sum",
            fontSize = 30.sp,
            color = when {
                sum < 10.0 -> Color.Cyan
                sum > 10.0 -> Color.Blue
                sum == 10.0 -> Color.Red
                else -> Color.Black
            }
        )

        Spacer()

        Button(onClick = onCalculate) {
            Text(text = "CALCULAR")
        }
    }
}

Modificar el fichero MainActivity.kt

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            EstadoTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    SumScreen()
                }
            }
        }
    }
}

fun String?.toDoubleOrZero() = this?.toDoubleOrNull() ?: 0.0

 

Código del proyecto Estado

Deja una respuesta