[英]Jetpack Compose AlertDialog Error: "@Composable invocations can only happen from the context of a @Composable function"
There appear to be an infinite number of explanations for this error on stackoverflow, none of which address my issue.关于 stackoverflow 上的这个错误似乎有无数种解释,但没有一个能解决我的问题。
I am building a compose alert dialog.我正在构建一个撰写警报对话框。 I am trying to show a list of options that can change depending on the data.
我正在尝试显示可以根据数据更改的选项列表。
@Composable
fun OptionSelectComposeDialog(
vm: OptionSelectDialogViewModel
){
...
val optionList = vm.optionList
Column {
if (openDialog.value) {
AlertDialog(
...
text = {
OptionListDialogContent(optionList)
},
...
)
}
}
In the OptionListDialogContent
composable function I'm trying to print out the list, but the Text
composable is giving an error.在
OptionListDialogContent
可组合项 function 中,我尝试打印出列表,但Text
可组合项给出错误。
OptionListDialogContent
@Composable
fun OptionListDialogContent(optionList: OptionList?) {
val optionItemArray = optionList?.getOptionItemArray(null)
LazyColumn() {
if (optionItemArray != null) {
optionItemArray.forEach { optionItem ->
Text(text = optionItem.toString()) // Error "@Composable invocations can only happen from the context of a @Composable function"
}
}
}
}
I suspected that the toString
call on the optionItem
is throwing this error, so I tried mapping the array to convert the array values to strings and still received this error.我怀疑对
optionItem
的toString
调用抛出了这个错误,所以我尝试映射数组以将数组值转换为字符串,但仍然收到这个错误。
OptionListDialogContent
After converting the array to strings: OptionListDialogContent
将数组转换为字符串后:@Composable
fun OptionListDialogContent(optionList: OptionList?) {
val optionItemArray = optionList?.getOptionItemArray(null)
val optionItemStringArray = optionItemArray?.map { it.toString()}?.toTypedArray()
LazyColumn() {
if (optionItemStringArray != null) {
optionItemStringArray.forEach { optionItem ->
Timber.d("This is working? - optionItemArray.size: %s", optionItemArray.size)
Text(text = optionItem) // Error "@Composable invocations can only happen from the context of a @Composable function"
}
}
}
}
Anyone see where the issue is?有人看到问题出在哪里吗? (I have verified that
optionItemArray
is not null) (我已验证
optionItemArray
不为空)
Turns out it is an issue with how I was using LazyColumn.事实证明这是我使用 LazyColumn 的方式的问题。 LazyColumn needs to receive an array size.
LazyColumn 需要接收数组大小。 There are different ways to do this, but this is how I did it:
有不同的方法可以做到这一点,但我是这样做的:
LazyColumn() {
if (optionItemStringArray != null) {
items(optionItemStringArray.size) { i ->
Row() {
Text(text = optionItemStringArray[i])
}
}
}
}
You are trying to put a lazy list(which is in OptionListDialogContent) inside a text field您正试图在文本字段中放置一个惰性列表(位于 OptionListDialogContent 中)
text = {
OptionListDialogContent(optionList)
},
The parameter needs to be compatible to take a composable function. In this case, the text does not do that.该参数需要兼容才能采用可组合的 function。在这种情况下,文本不会这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.