Dolphin
Dolphin

Reputation: 38985

is it possible to return a default value when using enum in dart

Now I am define a enum in dart like this:

enum LoginType {
  PHONE,
  WECHAT
}

extension ResponseStatusExtension on LoginType{
  static const statusCodes = {
    LoginType.PHONE: 1,
    LoginType.WECHAT: 2,
  };


  int get statusCode => statusCodes[this];
}

I am upgrade to flutter 2.0.1 and support null safety and now it tell me :

A value of type 'int?' can't be returned from the function 'statusCode' because it has a return type of 'int'.

but I want to make it return a default not null value to make the code rubust and did not have to handle null when using this enum. what should I do to make it return a default value? is it possible?

Upvotes: 0

Views: 2098

Answers (1)

julemand101
julemand101

Reputation: 31299

The reason for your error is that the [] operator on Map is nullable since it has this behavior:

The value for the given key, or null if key is not in the map.

https://api.dart.dev/stable/2.12.2/dart-core/Map/operator_get.html

If you are sure your Map always contains the requested key you can add a ! after the use of [] operator like this:

  int get statusCode => statusCodes[this]!;

This will make a null-check at runtime and fail if a null value is returned. But this should not be a problem if you are sure null is never returned from the Map.

Bonus tip

If you want to be able to have a default value returned from a Map in case the Map does not contain a given key you can add the following extension to Map:

extension MapDefaultValue<K, V> on Map<K, V> {
  V get(K k, V defaultValue) => containsKey(k) ? this[k] as V : defaultValue;
}

Notice that defaultValue must be a compatible type for key in the Map so you cannot use null as defaultValue if null are not allowed as a value in the Map.

Upvotes: 3

Related Questions