1

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 Answers2

2

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.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
0

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))
}
김용현
  • 1
  • 1
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney Jul 14 '23 at 17:01