Home > Enterprise >  conditional operation with types in jetpackCompose
conditional operation with types in jetpackCompose

Time:10-09

How to have a type to be optional and if it is not passed from outside than the second Text should not render. Right now gettin an error Type mismatch: inferred type is String but Boolean was expected

 @Composable
    fun FieldLabel(
        label: String,
        secondaryLabel: String?,
        modifier: Modifier = Modifier,
    
    ) {
        Text(
            text = label,
            textAlign = TextAlign.End,
            modifier = Modifier
                .fillMaxWidth(),
            fontWeight = FontWeight.Bold,
            fontSize = 24.sp,
            color = Color.Black,
        )
//How to write this part so that if there is not secondaryLabel provided than the text part does not render
       secondaryLabel ? Text(
            text = secondaryLabel,
            modifier = Modifier
                .fillMaxWidth()
            fontWeight = FontWeight.Bold,
            fontSize = 24.sp,
            color = Color.Black,
        ) : null
    }

CodePudding user response:

You can give a default value of null to secondaryLabel and if it's not null you can render that Text.

 @Composable
    fun FieldLabel(
        label: String,
        secondaryLabel: String? = null,
        modifier: Modifier = Modifier,
    
    ) {
        Text(
            text = label,
            textAlign = TextAlign.End,
            modifier = Modifier
                .fillMaxWidth(),
            fontWeight = FontWeight.Bold,
            fontSize = 24.sp,
            color = Color.Black,
        )
       if(secondaryLabel != null)
           Text(
               text = secondaryLabel,
               modifier = Modifier
                .fillMaxWidth()
               fontWeight = FontWeight.Bold,
               fontSize = 24.sp,
               color = Color.Black,
           )
    }
  • Related