Alexandr DA
Alexandr DA

Reputation: 39

How to make a constructor parameter not required?

I did not find an adequate answer on the Internet and decided to turn to you with a request to help me. When creating variables, I don't want all these variables to be required, but if I don't add the word required, then I get an error in the constructor. How can I add my variables to the constructor without the word required? It's really in my opinion not convenient to add all the variables with the required parameter and causes me a lot of problems. For example, here is my code, in which I do not want to add a parameter for various reasons, and I often see such examples

class AudioFile extends StatefulWidget {
  final AudioPlayer advancedPlayer;
  const AudioFile({Key? key, required this.advancedPlayer}) : super(key: key);

  @override
  State<AudioFile> createState() => _AudioFileState();
}

class _AudioFileState extends State<AudioFile> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Upvotes: 0

Views: 942

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63864

You can make data nullable

class AudioFile extends StatefulWidget {
  final AudioPlayer? advancedPlayer;
  const AudioFile({Key? key, this.advancedPlayer}) : super(key: key);

  @override
  State<AudioFile> createState() => _AudioFileState();
}

class _AudioFileState extends State<AudioFile> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Upvotes: 1

eamirho3ein
eamirho3ein

Reputation: 17950

if you want a variable be nullable use ? like this:

class AudioFile extends StatefulWidget {
  final AudioPlayer? advancedPlayer;
  const AudioFile({Key? key, this.advancedPlayer}) : super(key: key);

  @override
  State<AudioFile> createState() => _AudioFileState();
}

Upvotes: 1

Related Questions