Home > Net >  how to make a non required parameter in dart
how to make a non required parameter in dart

Time:02-22

I have different required parameters in flutter and I want to make one of them non required (colour). If I leave it without the required key, it give an error. How can I make it? Here is my code:

class DiscoverCardTemplate extends StatelessWidget {
  DiscoverCardTemplate({
    required this.textTop,
    required this.textMiddle,
    required this.textBottom,
    required this.coverImage,
    required this.onTap,
    this.colour,
  });

  final String textTop, textMiddle, textBottom, coverImage;
  final Function onTap;
  final Color colour;

CodePudding user response:

make it nullable means colour will be either null or colur_value.

class DiscoverCardTemplate extends StatelessWidget {
  DiscoverCardTemplate({
    required this.textTop,
    required this.textMiddle,
    required this.textBottom,
    required this.coverImage,
    required this.onTap,
    this.colour,
  });

  final String textTop, textMiddle, textBottom, coverImage;
  final Function onTap;
  final Color? colour;

or

add a default value for colour (if you didn't pass colour then it uses default value).

class DiscoverCardTemplate extends StatelessWidget {
  DiscoverCardTemplate({
    required this.textTop,
    required this.textMiddle,
    required this.textBottom,
    required this.coverImage,
    required this.onTap,
    this.colour = colour_value,
  });

  final String textTop, textMiddle, textBottom, coverImage;
  final Function onTap;
  final Color colour;

CodePudding user response:

Either make the

final Color colour;

as nullable:

final Color? colour;

Or, assign a default color in the constructor

this.colour = Colors.black,

  • Related