Home > Back-end >  How can I make a variable in the constructor make it optional (flutter)?
How can I make a variable in the constructor make it optional (flutter)?

Time:08-27

please help me solve the following problem. This part of my code:

class MeditationCard extends StatelessWidget {
  const MeditationCard({
    required this.title,
    required this.image,
    this.route});

final String title;
final String image;
final String route;
...

I need the route variable as optional, but when I remove the flag, I get an error and ask me to make the variable mandatory. Tried different approaches but didn't work for me This alert dialog

The parameter 'route' can't have a value of 'null' because of its type, but the implicit default value is 'null'.

CodePudding user response:

This happened because of null safety check.In order to set nullable variable, you should use ?, try this:

final String? route;

CodePudding user response:

You can make it nullable (?) or define default value

Example for nullable

class MeditationCard extends StatelessWidget {
  const MeditationCard({
    required this.title,
    required this.image,
    this.route});

final String title;
final String image;
final String? route;

CodePudding user response:

I know you got the proper answer to your question. But I wanted to mention another method to solve this issue that might help you in the future, which is to provide a default value. This way you avoid weird null errors and null checking.

class MeditationCard extends StatelessWidget {
  const MeditationCard({
    required this.title,
    required this.image,
    required this.route});

final String title;
final String image;
final String route = 'default route';
}

This way you ensure that the property 'route' has a value and is never null. And you can override it when you need to.

  • Related