0

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?

2 Answers 2

2

You show default values using ??

String firstString = widget.valA ?? "";
String secondString = widget.valB ?? "";
Text("$firstString / ${widget.value} / $secondString.")
Sign up to request clarification or add additional context in comments.

3 Comments

Nice solution! Thanks! I am still newbie to Dart. My other idea is to use named optional parameters with default values (but this came to my mind later).
Cool thats also a good solution.
What if we don't want to show the / if preceding value is null? How to do that?
1

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 ?? ""}");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.