Kotlin dataStore boolean value in Jetpack Compose switch type missmatch

33 views Asked by At

Im trying to store the boolean of the switch in kotlin dataStore and then set the switch value from the dataStore on change but i get a type mismatch:

Error from android studio

this is my settings page:

@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Settings(navController: NavHostController, modifier: Modifier = Modifier) {
    //data
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val dataStore = StoreGruSwitch(context)
    val savedGru = dataStore.getGruSwitch.collectAsState(initial = "")
    //Variables

    Scaffold(
        //Header
        topBar= {
            CenterAlignedTopAppBar(
                title = {
                    Text(text = "Settings")
                },
                navigationIcon = {
                    IconButton(onClick = {
                        navController.navigate("Start") {
                            popUpTo("Start") { inclusive = true }
                        }
                    }) {
                        Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back arrow")
                    }
                },
            )
        },
        //mer

    ) { contentPadding ->
        //Content
        Column(modifier.padding(contentPadding)){
            //Switches
            Switch(checked = savedGru.value, onCheckedChange = { scope.launch { dataStore.saveGruSwitch(savedGru.value) } })
        }
    }
}

This is where i store the data:

class StoreGruSwitch(private val context: Context) {

    //To make sure there is one instance
    companion object{
        private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "GRU")
        val GRU_Switch = booleanPreferencesKey("gru_switch")
    }

    //Get variable
    val getGruSwitch: Flow<Any> = context.dataStore.data
        .map { preferences ->
            preferences[GRU_Switch] ?: ""
        }

    //Save variable
    suspend fun saveGruSwitch(name: Boolean){
        context.dataStore.edit { preferences ->
            preferences[GRU_Switch] = name
        }
    }
}

I have tried searching around without finding anything to help me specific case.

0

There are 0 answers