Jetpack Compose Toast Shows Again and Again? FIXED in Seconds!
If you're seeing your Toast message repeat every time a composable recomposes, you're not alone. It's a common issue faced by developers working with Jetpack Compose.
In this quick tutorial, you'll learn why this happens and the simple fix using LaunchedEffect
that stops the Toast from being triggered multiple times.
Watch this short video for explanation with an example.
The Problem
Many developers write Toasts like this inside a composable:
fun ToastContent() {
val context = LocalContext.current
Toast.makeText(context,
"Welcome!",
Toast.LENGTH_SHORT)
.show()
}
The Fix — Use LaunchedEffect
To show a Toast only once (even during recompositions), wrap it inside a LaunchedEffect
block.
@Composable
fun ToastContent() {
val context = LocalContext.current
LaunchedEffect(Unit) {
Toast.makeText(context,
"Welcome!",
Toast.LENGTH_SHORT)
.show()
}
}
Why This Works
- Jetpack Compose is declarative — anything inside a composable can be called multiple times.
- LaunchedEffect provides a controlled side-effect block that runs only when the key changes.
Pro Tip
You can also replace Unit
with any key if you want the Toast to run only when that value changes:
LaunchedEffect(myKey) {
Toast.makeText(context,
"Welcome!",
Toast.LENGTH_SHORT)
.show()
}
Wrapping Up
That’s it — now your Toast behaves like it should! No more surprises during recompositions.
No comments:
Post a Comment
Share your thoughts ...