我正在遵循this个文档,并试图在我的应用程序中实现数据存储首选项,但我在做这件事上遇到了麻烦.
我有下面的代码,错误在三行:
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.mymentalhealth.ui.theme.MyMentalHealthTheme
import kotlinx.coroutines.flow.Flow
import java.util.prefs.Preferences
import androidx.compose.runtime.getValue
import kotlinx.coroutines.flow.map
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") // Error 1
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyAppTheme {
val ACCOUNT_TYPE = stringPreferencesKey("account_type")
val accountTypeFlow: Flow<String> = context.dataStore.data // Error 2
.map { preferences -> // Error 3
preferences[ACCOUNT_TYPE] ?: ""
}
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Text(text = "Hello, World")
}
}
}
}
}
错误1:属性委托必须具有‘getValue(Context,KProperty*>;)’方法.以下函数都不适用. Kotlin.Properties.ReadOnlyProperty中定义的getValue(Context,KProperty<;*>;)
错误2:无法使用提供的参数调用以下函数. context()在kotlin.coroutines.jvm.internal.CompletedContinuation中定义 context()在kotlinx.coroutines.flow.internal.NoOpContinuation中定义
错误3:无法推断此参数的类型.请明确说明.
除了使用字符串而不是int之外,我完全遵循文档.我也不确定如何访问和使用该变量(例如,在if语句中实现它).任何帮助都将不胜感激.谢谢.