Interesting
Interesting

Reputation: 325

The default value of an optional parameter must be constant. Dart

I tried to make a default map parameter but it just goes errors for some reason,

var size = {
  "width": 1920,
  "height": 1080,
};

class MyClass {
  myFunction([String MyParam = "Sup!", Map background_size = size]) async {
    return background_size.width;
  }
}

It only gives me an errors like this The default value of an optional parameter must be constant. Can someone tell me which lines I type wrong?

Upvotes: 2

Views: 2556

Answers (1)

Cyrax
Cyrax

Reputation: 827

Solution 1

Define size as const

const size = {
  "width": 1920,
  "height": 1080,
};

class MyClass {
  myFunction([String MyParam = "Sup!", Map background_size = size]) async {
    return background_size.width;
  }
}

Solution 2

Set value if background_size is not set

var size = {
  "width": 1920,
  "height": 1080,
};

class MyClass {
  myFunction([String MyParam = "Sup!", Map? background_size]) async       {
    final _background_size = background_size ?? size;
    return _background_size.width;
  }
}

Upvotes: 2

Related Questions