Search code examples
flutterdartdart-null-safety

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

Solution

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