Home > Back-end >  Conditionally show / render values (none-null String values) in UI (Flutter Text widget)
Conditionally show / render values (none-null String values) in UI (Flutter Text widget)

Time:08-22

I have three String variables, that I have to show in one Text() widget using string interpolation. But I of course don't like to show strings that have null value.

So I have got:

String? valA; // might be null or not
String value = "Never null !";
String? valB; // might be null or not

I have simple Text() widget, which looks like:

Text("${widget.valA} / ${widget.value} / ${widget.valB}."

If string is null I would like to have empty string instead of null value.

What is the proper and nice solution to this - rather simple - problem?

CodePudding user response:

You show default values using ??

String firstString = widget.valA ?? "";
String secondString = widget.valB ?? "";
Text("$firstString / ${widget.value} / $secondString.")

CodePudding user response:

Just to complement Kaushik's excelent answer above, if you dont like declaring aditional variables or just pull data directly from an API, you could do the if condition in the string:

Text("${valA ?? ""} / ${value} / ${valB ?? ""}");
  • Related