简体   繁体   中英

How to default nullable ints to 0

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?

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; (myClass.anotherCount != null) ? myClass.anotherCount : 0; but much less verbose.

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.

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