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(AnaApplication.appContext))
}