I'm trying to migrate an Android Jetpack Compose project to compose multiplatform. How can we use context in the composables.
val context = LocalContext.current
I can't access the LocalContext
I'm trying to migrate an Android Jetpack Compose project to compose multiplatform. How can we use context in the composables.
val context = LocalContext.current
I can't access the LocalContext
LocalContext
stores Context
object, which is Android only class, so you can only use it in androidMain
.
You can create your own local context analog, and implement the needed actions with expect
/actual
.
shared/androidMain/MyApplication.kt
class MyApplication: Application() {
companion object {
lateinit var appContext: Context
}
override fun onCreate() {
super.onCreate()
appContext = applicationContext
}
}
If you need context in your acual fun, use MyApplication.appContext!
example)
actual fun getDataBase(): Database {
return Database(DatabaseDriverFactory(MyApplication.appContext))
}
===============================================
I checked the comments again today, April 16, 2024, and confirmed that it still doesn't work.
I resolved it in the following way:
expect object AppContext
import android.content.Context
import java.lang.ref.WeakReference
actual object AppContext {
private var value: WeakReference<Context?>? = null
fun set(context: Context) {
value = WeakReference(context)
}
internal fun get(): Context {
return value?.get() ?: throw RuntimeException("Context Error")
}
}
actual object AppContext
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
AppContext.apply { set(applicationContext) }
}
}
actual fun dataStore(): DataStore<Preferences> {
return createDataStore (
producePath = {AppContext.get().filesDir.resolve(Constants.dataStoreFileName).absolutePath }
)
}
throw RuntimeException("Context Error")
–
Shimberg © 2022 - 2024 — McMap. All rights reserved.