flutter-tips-and-tricks icon indicating copy to clipboard operation
flutter-tips-and-tricks copied to clipboard

extension OrDefault<T> on T does not work

Open gaddlord opened this issue 3 years ago • 1 comments
trafficstars

As suggested at https://github.com/vandadnp/flutter-tips-and-tricks/blob/main/tipsandtricks/default-value-for-optionals-in-dart/default-value-for-optionals-in-dart.md

I declared:

extension OrDefault<T> on T {
  T get orDefault {
    final value = this;
    if (value == null) {
      return {
        int: 0,
        String: '',
        double: 0.0,
        num: 0,
        bool: false,
        Map: {},
        List: [],
        Set: {},
      }[T] as T;
    } else {
      return value;
    }
  }
}

  test('Test ObjectExtension.orDefault()', () async {
    const int? nullInt = null;
    expect(nullInt.orDefault, 0); // fails since T is int? and returns null instead of 0.
  });

gaddlord avatar Jul 26 '22 16:07 gaddlord

Hello Gaddlord, according to the Default Value for Optionals in Dart you need to associate your int? to OrDefault extension that is a nullable T?, but in your code you bind to a generic T which is non-nullable, so nullable int keeps the null value because the extension waiting for a non-nullable variable. You just need to change this: extension OrDefault<T> on T {

to this: extension OrDefault<T> on T? {

And this should do it. Hope this can help.

marcoedomingos avatar Aug 26 '22 07:08 marcoedomingos