How to use Context in a compose multiplatform projeect?
Asked Answered
S

2

9

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

Sunup answered 10/5, 2023 at 2:38 Comment(0)
G
5

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.

Genarogendarme answered 4/7, 2023 at 3:40 Comment(0)
B
4

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:

  1. commonMain
expect object AppContext
  1. androidMain
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")
    }
}
  1. iosMain
actual object AppContext
  1. androidApp > MyApp
class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        AppContext.apply { set(applicationContext) }
    }
}
  1. using
actual fun dataStore(): DataStore<Preferences> {
    return createDataStore (
        producePath = {AppContext.get().filesDir.resolve(Constants.dataStoreFileName).absolutePath }
    )
}
Bemock answered 9/7, 2023 at 15:18 Comment(3)
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?Washer
Does not work for me -Systole
@Bemock does it work? I hope I dont get random crashes because of the throw RuntimeException("Context Error")Shimberg

© 2022 - 2024 — McMap. All rights reserved.