1

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?

Civan Öner
  • 65
  • 1
  • 8

2 Answers2

7

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
  });
Martijn
  • 114
  • 5
0

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

Rohit Mandiwal
  • 10,258
  • 5
  • 70
  • 83