Civan Öner
Civan Öner

Reputation: 65

Flutter 2.0 / Dart - How to create a constructor with optional parameters?

I created a class and want some of the parameters to be optional, but can't figure out how to do it.

class PageAction {
  PageState state;
  PageConfiguration page;
  List<PageConfiguration> pages;
  Widget widget;

  PageAction({
    this.state = PageState.none,
    this.page, // Optional
    this.pages, // Optional
    this.widget, // Optional
  });

I get the suggestion to add "required", but that is not what I need. Can someone help and explain please?

Upvotes: 1

Views: 5338

Answers (2)

Rohit Mandiwal
Rohit Mandiwal

Reputation: 10462

I have shared a detailed information on constructors, Please refer my answer https://stackoverflow.com/a/69081615/563735

Upvotes: 0

Martijn
Martijn

Reputation: 114

The title says Flutter 2.0 but I assume you mean with dart 2.12 null-safety. In your example all the parameters are optional but this will not compile cause they are not nullable. Solution is to mark your parameters as nullable with '?'.

Type? variableName // ? marks the type as nullable.
class PageAction {
  PageState? state;
  PageConfiguration? page;
  List<PageConfiguration>? pages;
  Widget? widget;

  PageAction({
    this.state = PageState.none,
    this.page, // Optional
    this.pages, // Optional
    this.widget, // Optional
  });

Upvotes: 7

Related Questions