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

Issue

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

Answered By – Martijn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published