简体   繁体   English

如何在小部件树中使用 null 安全性编写代码

[英]How to write coditional with null safety in widget tree

I have a problem with displaying dynamically Text widget based on String null safety value.我在基于 String null 安全值动态显示文本小部件时遇到问题。 So, If I'm writing conditions like that:所以,如果我写这样的条件:

String? _selected;
String _placeholer = "select";


         Row(
            children: [
              if (_selected != null) Text(_placeholer) else Text(_selected!),
            ],
          ),

or或者

         Row(
            children: [
              _selected!.isEmpty ? Text(_placeholer) : Text(_selected!),
            ],
          ),

Console is returning this error:控制台返回此错误:

Unexpected null value.意外的 null 值。

And on the view I have red container instead of this Text.在视图上我有红色容器而不是这个文本。 How can I fix it?我该如何解决?

It seems like you made a mistake here.看来你在这里犯了一个错误。

            children: [
              if (_selected != null) Text(_placeholer) else Text(_selected!),
            ],

Change it like this:像这样改变它:

            children: [
              if (_selected == null) Text(_placeholer) else Text(_selected!),
            ],

Much better version would be like this:更好的版本是这样的:

children: [
   Text(_selected ?? _placeholder)
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM