I will show in 10 Text widgets, some variables. This variables can are Strings and can be empty ''
There is a simpler way to do this verification than this, one by one: ?
object.name.isNotEmpty ? object.name : "not typed"
try this
check if it is null string
object.name ?? 'default value'
check if its a null or empty string
object.name?.isEmpty ?? 'default value'
The ?? double question mark operator means "if null". Take the following expression, for example. String a = b ?? 'hello'; This means a equals b, but if b is null then a equals 'hello'.
object.name ??= "not typed";
It assigns "not typed" if object.name is empty.
You can also use double question mark to check if something else is null and if it is assign the other value:
object.name = null ?? "not typed"; // result: object.name = "not typed";
object.name = "typed" ?? "not typed"; // result: object.name = "typed";
EDIT:
If you need to check if something is an empty string, you can use tenary expression, but there is no more operators or string methods:
object.name = object.name != null && object.name.isNotEmpty ? object.name : "not typed";
I think that the most convenient way to provide a default value is to extend the String class.
So, create a class StringExtension with a method like this:
extension StringExtension on String {
String def(String defaultValue) {
return isNotEmpty ? this : defaultValue;
}
}
In your view, you can now simply do:
import 'package:code/helpers/string_extension.dart';
String value;
@override
Widget build(BuildContext context) {
return Text(value.def("Unknown"))
}
If I understand your question correctly you want to simply check if something is null and assign to a variable accordingly. To do this you can use the OR operator like this:
var x = object.name || "not typed"
if object.name is truthy (as in not an empty string "") then that will be assigned to your variable (in this case x). If object.name is an empty string/falsey then "not-typed" will be assigned to x.
To check if a string is null or not by using ternary operator in JS you can use:
let n = ""
console.log(n.length > 0 ? "The string is not empty" : "The string is empty");
Try this:
object.name != Null ? object.name : "not typed"
or
object.name != '' ? object.name : "not typed"