Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

extension OrDefault<T> on T does not work #15

Open
gaddlord opened this issue Jul 26, 2022 · 1 comment
Open

extension OrDefault<T> on T does not work #15

gaddlord opened this issue Jul 26, 2022 · 1 comment

Comments

@gaddlord
Copy link

gaddlord commented Jul 26, 2022

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.
  });
@Marco4763
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants