[英]How to write coditional with null safety in widget tree
我在基于 String null 安全值动态显示文本小部件时遇到问题。 所以,如果我写这样的条件:
String? _selected;
String _placeholer = "select";
Row(
children: [
if (_selected != null) Text(_placeholer) else Text(_selected!),
],
),
或者
Row(
children: [
_selected!.isEmpty ? Text(_placeholer) : Text(_selected!),
],
),
控制台返回此错误:
意外的 null 值。
在视图上我有红色容器而不是这个文本。 我该如何解决?
看来你在这里犯了一个错误。
children: [
if (_selected != null) Text(_placeholer) else Text(_selected!),
],
像这样改变它:
children: [
if (_selected == null) Text(_placeholer) else Text(_selected!),
],
更好的版本是这样的:
children: [
Text(_selected ?? _placeholder)
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.