Valynk
Valynk

Reputation: 477

Jetpack Compose empty string in WebView

The variable singleArticle.content I used in the AndroidView is returning an empty value. But if I display it outside AndroidView the value appear correctly. Can someone know please what's the issue with my code

@Composable
fun ArticleDetailScreen(
    navController: NavController,
    viewModel: ArticleDetailViewModel = hiltViewModel()
) {
    ...
    CustomWebView(viewModel.article.value)
    ...
}

@Composable
fun CustomWebView(singleArticle: Article) {
    AndroidView(
        factory = { context ->
            WebView(context).apply {
                loadData(singleArticle.content, "text/html", "UTF-8")
            }
        },
    )
}

Upvotes: 1

Views: 1200

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 88082

A possible reason is that your singleArticle.content initially empty, and gets updated after view appears.

AndroidView factory is getting called only once when the view is created. To sync it with Compose state updates, you should use update block:

AndroidView(
    factory = { context ->
        WebView(context)
    },
    update = {
        it.loadData(singleArticle.content, "text/html", "UTF-8")
    },
)

Upvotes: 4

Related Questions