Search code examples
flutterconstructoroptional-parametersflutter-navigationdart-null-safety

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?


Solution

  • 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
      });