简体   繁体   中英

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. 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.

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)
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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