Reputation: 185
I got a List of objects that came from a rest api, I deserialized it and got a list of MyClass, which has a property that may be null:
abstract class MyClass implements Built<MyClass, MyClassBuilder> {
MyClass._();
factory MyClass([updates(MyClassBuilder b)]) = _$MyClass;
int get id;
String get name;
int get aCount;
@nullable
int get anotherCount;
static Serializer<MyClass> get serializer => _$MyClassSerializer;
}
I have a ListTiles that has a list of MyClass which creates a text, the placeholder for anotherCount
displays null if the value is null.
List<Widget> buildListTiles() {
return _MyClassList
.map((myClass) =>
ListTile(
title: Text('id: ${myClass.id}-${myClass.name}'),
subtitle: Text(
'aCount: ${myClass.aCount} anotherCount: ${myClass.anotherCount}',
),
))
.toList();
}
Displays:
aCount: 5 anotherCount: null
I want:
aCount: 5 anotherCount: 0
Is there a way that it can default to 0 since it's an int?
Upvotes: 1
Views: 809
Reputation: 3219
You can always use the ??
operator to return a default value in the case of null. For example, you could use the following to display 0
instead of null
:
Text('aCount: ${myClass.aCount} anotherCount: ${myClass.anotherCount ?? 0}')
This is the equivalent of (myClass.anotherCount != null) ? myClass.anotherCount : 0;
but much less verbose.
Upvotes: 4
Reputation: 2271
Try changing your
int get anotherCount;
to
int get anotherCount => (anotherCount != null) ? anotherCount : 0;
This way, if the value is null, it would return 0 instead.
Didn't know int can be null tho. I've always thought it would be 0 if unassigned/not used.
Upvotes: 0