如何解决"The argument type 'String?' can't be assigned to the parameter type 'String' " - 颤振



输入图像描述到"参数类型'String ' ?'不能分配给参数类型'String'"下面的代码

static extractText(VisionText) {String text = ";

for (TextBlock block in visionText.blocks) {
for (TextLine line in block.lines) {
for (TextElement word in line.elements) {
text = text + word.text + ' ';
}
text = text + 'n';
}
}
return text;

}

"参数类型'String ' ?'不能分配给参数类型'String'">

当期望一个非空的String值,但提供了一个可空的String?时,会发生此错误。

在这种情况下,如果你的text是一个非空的String和你的word.text是一个可空的String?,你可以这样做:

text += (word?.text ?? '') + ' ';

这里,?.运算符用于检查word是否为空,然后获取text的值。??word?.text为null的情况下,则取空字符串作为值。因此,该值始终是非空值。

你可以在这里阅读更多的文档。

你可以试试:

text = text + (word?.text ?? '' ) + ' ';

相关内容