如何将积分系统添加到应用程序首选项DataStore Jetpack Compose中



我正在开发一个测验应用程序,我正试图在该应用程序中添加一个积分系统以便每次用户答对问题时,他都会得到+1pts。以及用于存储我使用jetpack compose preferences的点数据存储。问题是,每当我想在已经保存的点上添加一个点时,它都不起作用。

这是我的点数数据

class PointsData(private val context: Context) {
//create the preference datastore
companion object{
private val Context.datastore : DataStore<Preferences> by preferencesDataStore("points")
val CURRENT_POINTS_KEY = intPreferencesKey("points")
}
//get the current points
val getpoints: Flow<Int> =context.datastore.data.map { preferences->
preferences[CURRENT_POINTS_KEY] ?: 0
}
// to save current points
suspend fun SaveCurrentPoints(numPoints : Int){
context.datastore.edit {preferences ->
preferences[PointsData.CURRENT_POINTS_KEY] = numPoints
}
}
}

保存点方法

class SavePoints {
companion object {
@Composable
fun savepoints(numPointsToSave : Int) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val datastore = PointsData(context)
LaunchedEffect(1) {
scope.launch {
datastore.SaveCurrentPoints(numPointsToSave)
}
}
}
}
}

每当我想从数据存储中获得点数时,我都会使用

val pointsdatastore = PointsData(context)
val currentpoints = pointsdatastore.getpoints.collectAsState(initial = 0)
//display it as text for example
Text(text = currentpoints.value.toString(), fontSize = 30.sp, fontWeight = FontWeight.Bold,
color = Color.White)

并且为了进行我想要的操作(添加+1个已经存在的点,我进行

val pointsdatastore = PointsData(context)
val currentpoints = pointsdatastore.getpoints.collectAsState(initial = 0)
SavePoints.savepoints(numPointsToSave =  currentpoints.value + 1)

但它似乎不起作用,因为点数总是保持在1。

如果你知道问题出在哪里,请帮忙

我自己找到了答案,但对于任何陷入同样情况的人来说,解决方案是PointsData中的另一种方法(查看问题提供的代码(

方法是:

suspend fun incrementpoints(){
context.datastore.edit { preferences->
val currentpoints = preferences[CURRENT_POINTS_KEY] ?: 0
preferences[CURRENT_POINTS_KEY] = currentpoints + 1
}
}

(如果您想要递减而不是递增,您可以将+更改为-(

现在在PointsMethod(查看问题提供的代码(中,您应该添加

@Composable
fun incrementpoints() {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val datastore = PointsData(context)
LaunchedEffect(key1 = 1) {
scope.launch {
datastore.incrementpoints()
}
}
}

最新更新