如何在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",
)
}
1条答案
按热度按时间fykwrbwg1#
要将collectAsState与Flow值一起使用,必须在build.gradle文件中添加此依赖项