How to use Context in a compose multiplatform projeect?

1.3k views Asked by At

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

2

There are 2 answers

0
Phil Dukhov On

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.

2
김용현 On

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))
}