android 如何在Jetpack Compose中使用Datastore读取和保存Switch数据?

2g32fytz  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(241)

如何在Jetpack Compose中使用Datastore读取和保存Switch数据?我需要存储在数据存储和加载状态时,应用程序被关闭,并由用户再次打开当前状态。

class DataStoreUtil(private val context: Context) {

    companion object {
        private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("settings")
        val FORCE_DARK_THEME = booleanPreferencesKey("force_dark_theme")
    }

    val getForceDarkTheme: Flow<Boolean> = context.dataStore.data
        .map { preferences ->
            preferences[FORCE_DARK_THEME] ?: true
        }

    suspend fun saveForceDarkTheme(value: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[FORCE_DARK_THEME] = value
        }
    }
}

@Composable
fun MySwitch() {
    val checkedState = remember { mutableStateOf(false) }
    Switch(
        checked = checkedState.value,
        onCheckedChange = { checkedState.value = it }
    )
    Text(
        text = if(checkedState.value) "foo" else "bar",
    )
}
fykwrbwg

fykwrbwg1#

class DataStoreUtil(private val context: Context) {

    companion object {
        private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("settings")
        val FORCE_DARK_THEME = booleanPreferencesKey("force_dark_theme")
    }

    val getForceDarkTheme: Flow<Boolean> = context.dataStore.data
        .map { preferences ->
            preferences[FORCE_DARK_THEME] ?: true
        }

    suspend fun saveForceDarkTheme(value: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[FORCE_DARK_THEME] = value
        }
    }
}

@Composable
fun MySwitch() {

   val scope = rememberCoroutineScope()
   //creating an object of your datastore
    val dataStore = DataStoreUtil(LocalContext.current)
   //retrieving the boolean value from the data store as a state
    val switchState by dataStore.getForceDarkTheme.collectAsState()

    Switch(
        checked = switchState,
        onCheckedChange = {
scope.launch{
 dataStore.saveForceDarkTheme(it) 
}
}
    )
    Text(
        text = if(checkedState.value) "foo" else "bar",
    )
}

要将collectAsState与Flow值一起使用,必须在build.gradle文件中添加此依赖项

implementation("androidx.lifecycle:lifecycle-runtime-compose:2.6.0-beta01")

相关问题