166
fun createListItem(itemIndex: Int) {
    Padding(left = 8.dp, right = 8.dp, top = 8.dp, bottom = 8.dp) {
        FlexRow(crossAxisAlignment = CrossAxisAlignment.Center) {
            expanded(1.0f) {
                Text("Item $itemIndex")
            }
            inflexible {
                Button(
                    "Button $itemIndex",
                    style = ContainedButtonStyle(),
                    onClick = {
                        Toast.makeText(
                            this@MainActivity,
                            "Item name $itemIndex",
                            Toast.LENGTH_SHORT
                        ).show()
                    })
            }
        }
    }
}

I try to make Toast in a normal way. but I got the error I tried a lot of multiples source but failed.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Mr. Tayyab MuGhal
  • 1,791
  • 2
  • 10
  • 11
  • did you add the "@Composable" annotation? – Spark.Bao Nov 07 '19 at 07:26
  • yes did. @Composable annotation – Mr. Tayyab MuGhal Nov 07 '19 at 07:30
  • You might want to explain exactly what your problem was. I have used `Toast` in `onClick` handlers in Compose without a problem. If you were getting a compile error, please provide the complete details of the error. If you were getting a runtime error, please edit your question and post the stack trace. – CommonsWare Nov 07 '19 at 12:04
  • FYI: while the answers below are valid, the compose team now recommends using `Snackbar` over `Toast` in Compose: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1614352257404200?thread_ts=1614333574.353800&cid=CJLTWPH7S. – Raman Apr 19 '21 at 18:57

12 Answers12

317

Update March 2021: The previous answer has been deprecated. You should now use:

val context = LocalContext.current

Previous answer for reference:

You can access to context with define ambientContext.

Example:

val context = ContextAmbient.current
Raka Adi Nugroho
  • 3,403
  • 1
  • 8
  • 6
  • compose is declarative & as a tree, so if you have complex trees and you need some state that could not provided from root component, you can use ambient or memo – Raka Adi Nugroho Nov 20 '19 at 03:33
  • 1
    Is there any doc that explains the use of this unaryPlus operator? I can't find anything solid to understand what it is and how to use it @Raka – Vladimir Jan 29 '20 at 03:43
  • When I add val context = +ambient(ContextAmbient) to Clickable then get java.lang.IllegalStateException: Composition requires an active composition context – Alex Zezekalo Feb 06 '20 at 15:04
  • please show your code (by gist.github.com) @AlexZezekalo – Raka Adi Nugroho Feb 07 '20 at 07:38
  • 1
    @RakaAdiNugroho I found out that I used a wrong place for getting context: firstly I wrote val context = +ambient(ContextAmbient) inside *Clickable* and it was the reason of that exception. Then I put this line out of the *Clickable* to the head of the function and everything became Ok. My fault. – Alex Zezekalo Feb 07 '20 at 11:47
  • `LocalContext.current` can not be used in coroutine scope. This happens typically, when Android forces you to do something in a different thread, than the UI thread. – ceving Dec 13 '22 at 10:02
  • I haven't seen this explicitly stated, but it appears Ambient has been removed/rename something else? I found this: https://lcdsmao.dev/jetpack-compose-what-is-the-difference-between-ambient-and-static-ambient/ describing what it was. This seems related: https://developer.android.com/jetpack/androidx/releases/compose-runtime Renamed Ambients to match the Ambient -> CompositionLocal rename. Ambients used to be named AmbientFoo, now CompositionLocals are named LocalFoo. (I2d55d) I found ambients in old sample code: https://github.com/android/compose-samples/tree/main/Jetchat – MathiasTCK Mar 18 '23 at 22:42
72

ContextAmbient and AmbientContext has been deprecated.

You can replace them with LocalContext

Example:

val context = LocalContext.current
Ahmed Abdalla
  • 2,356
  • 2
  • 14
  • 27
  • How can I use this `val context = LocalContext.current` as a global variable in my Activity? – gaurav kumar Feb 10 '23 at 10:12
  • @gauravkumar I think the most you can do is declaring it as the first line in `setContent` method because it only works inside composable function. If you need a context outside `setContent`, just use `this`. – adravel May 12 '23 at 09:18
34

ContextAmbient.current is deprecated as of alpha-09.

AmbientContext.current is deprecated. I think as of alpha-11.

LocalContext.current is how you get the context in a composable now.

mitch
  • 797
  • 8
  • 14
33

The way to do this has been updated. It's now:

val context = LocalContext.current

LocalContext docs

Ryan M
  • 18,333
  • 31
  • 67
  • 74
29

ContextAmbient and AmbientContext is deprecated

Update

Now Jetpack way to do this has been updated. It's now:

val context = LocalContext.current
Anas Mehar
  • 2,739
  • 14
  • 25
26

LocalContext.current - is the right approach. But the problem is you can't use LocalContext.current inside @Composable function

You need to create separate function to use Context

Sample code

@Composable
fun DoneButton() {
    val context = LocalContext.current
    Button(onClick = { showToast(context, "Button clicked")}) {
        Text(name = "Done")
    }
}

fun showToast(context: Context, msg: String) {
    Toast.makeText(context, msg, Toast.LENGTH_LONG).show()
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Ranjithkumar
  • 16,071
  • 12
  • 120
  • 159
14

ContextAmbient.current has been deprecated, use val context = LocalContext.current instead.

Brian Mutiso
  • 299
  • 6
  • 10
7

Some useful if you need get context as Activity from last Android Studio template:

val view = LocalView.current
(view.context as Activity).<activity method>

Better solution

fun Context.getActivity(): Activity? = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.getActivity()
    else -> null
}

val activity = LocalContext.current.getActivity()
brucemax
  • 754
  • 8
  • 15
6

For getting context in jetpack compose:

val context = ContextAmbient.current

Working on 0.1.0-dev14

How to use it in TOAST:

@Composable
fun cardViewImplementer(item: Int) {
   val context = ContextAmbient.current
   Card(
     shape = RoundedCornerShape(10.dp),
     modifier = Modifier.padding(10.dp)
   ) {
     Box(
        modifier = Modifier
            .fillMaxWidth()
            .drawShadow(5.dp)
            .clickable(onClick = {
                Toast.makeText(context, "Clicked $item", Toast.LENGTH_SHORT).show()
            }), children = {

        })
}

For accessing the Resource:

Text("Read this string: "+context.getString(R.string.name))
Ali Azaz Alam
  • 1,782
  • 1
  • 16
  • 27
5

Issues with compose_version = '1.0.0-alpha12' ? AmbientContext is now LocalContext

Gianluca Veschi
  • 1,239
  • 1
  • 14
  • 20
2
val context = LocalContext.current
Toast.makeText(context,"Hello Compose",Toast.LENGTH_LONG).show()
1

You can use the LocalUriHandler:

val handler = LocalUriHandler.currenthandler 

Button( 
    onClick = { handler.openUri("https://www.stackoverflow.com") } 
) {    
     Text("Open") 
} 
Nazanin Nasab
  • 595
  • 8
  • 18