Home > Software design >  Jetpack Compose empty string in WebView
Jetpack Compose empty string in WebView

Time:10-22

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")
            }
        },
    )
}

CodePudding user response:

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")
    },
)
  • Related