Ibramazin
Ibramazin

Reputation: 1018

How to correctly pass a parameter to a lambda in onClick using Jetpack Compose

I am trying to call a composable which has a parameter

This is the composable I want to call onClick

@Composable
fun ShowCustomChromeTab(articleUrl: String){
.......//it has a parameter 
}

Now when user clicks on an item:

@Composable
fun ArticleItem(article: Article, onClick: () -> Unit){
Box(
    modifier = Modifier
        .clickable {
            onClick(article.url)
        },
)

This is how I am now using it

var shouldOpenChromeTab by rememberSaveable { mutableStateOf(false) }
var articleUrl by rememberSaveable { mutableStateOf("") }


if (shouldOpenChromeTab){
    ShowCustomChromeTab(articleUrl)
}

ArticleItem(it, onClick = { url->
  shouldOpenChromeTab = true
  articleUrl = url
 }
)}

PROBLEM

When I click on the item, it does open the url as expected, but when I press back and click on the same item, nothing happens...

It seems that value gets reset to false... when I go back, even though I am using rememberSaveable??

Upvotes: 1

Views: 3739

Answers (1)

talhatek
talhatek

Reputation: 355

The problem is that value is still true that is why nothing happens.
You have to reset to false after navigating to chrome.

var shouldOpenChromeTab by rememberSaveable { mutableStateOf(false) }
var articleUrl by rememberSaveable { mutableStateOf("") }


if (shouldOpenChromeTab){
    ShowCustomChromeTab(articleUrl)
    shouldOpenChromeTab = false
}

ArticleItem(it, onClick = { url->
  shouldOpenChromeTab = true
  articleUrl = url
 }
)}

Upvotes: 2

Related Questions