android 我创建的DataStore代码出错,即使我正确地创建了它

lnlaulya  于 2023-05-12  发布在  Android
关注(0)|答案(1)|浏览(257)

我试着创建一个数据存储来保存用户的输入。不管怎样,我遵循了所有的步骤,但有些部分是红色的。
我实现了必要的依赖关系。这就是我尝试过的。在Android Studio中,带星号的代码片段为红色。

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.prefs.Preferences
import androidx.datastore.core.Preferences

class StoreUserInput(private val context: Context) {

    companion object {
        private val Context.dataStore: DataStore<Preferences> by **preferencesDataStore("FirstName")**
        val FIRST_NAME_KEY = stringPreferencesKey("first_name")

    }

    val getFirstName: Flow<String?> = context.dataStore.data
        .map {
            preferences ->
            **preferences[FIRST_NAME_KEY]** ?: ""
        }

     suspend fun saveFirstName(name: String) {
        context.dataStore.**edit** { **preferences** ->
            preferences[FIRST_NAME_KEY] = name
        }
    }

}
6gpjuf90

6gpjuf901#

Context.datastore中删除类型

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class StoreUserInput(private val context: Context) {

    companion object {
        private val Context.dataStore by preferencesDataStore("FirstName")
        val FIRST_NAME_KEY = stringPreferencesKey("first_name")

    }

    val getFirstName: Flow<String?> = context.dataStore.data
        .map {
                preferences ->
            preferences[FIRST_NAME_KEY] ?: ""
        }

    suspend fun saveFirstName(name: String) {
        context.dataStore.edit { preferences ->
            preferences[FIRST_NAME_KEY] = name
        }
    }

}

执行https://github.com/googlecodelabs/android-datastore/tree/preferences_datastore时遵循官方文档

相关问题