Named parameters can't start with an underscore on null safe flutter

Viewed 1053

I am not sure why this fails? How can this be fixed?

As per this https://dart.dev/tools/diagnostic-messages#private_optional_parameter it's being told to make them without underscores. But that makes the variable public instead of being a private?

class ContactElement extends StatelessWidget {


  final IconData _icon;
  final String _heading;
  final String _describer;

  const ContactElement({
    Key? key,
    required this._icon,
    required this._heading,
    required this._describer,
  }) : super(key: key);
}

please help

3 Answers

Underscore means a private field for Dart (more here)

class ContactElement extends StatelessWidget {
  const ContactElement({
    Key? key,
    required IconData icon,
    required String heading,
    required String describer,
  }) : _icon = icon,
       _heading = heading,
       _describer = describer,
       super(key: key);
  
  // Private fields
  final IconData _icon;
  final String _heading;
  final String _describer;

  // If you want that other parts of the code could to these
  // fields, use getters and setters. Here is a getter example. 
  IconData get icon => _icon;
  ...
}

Got this answer in comments from @pskink. Posting it here

final IconData _icon;
final String _heading;
final String _describer;

ContactElement({
  IconData icon,
  String heading,
  String describer,
}) : _icon = icon, _heading = heading, _describer = describer;

This is not possible since if you define a constructor for private variables you can not instantiate the class outside it's file since the variables are private, so the alternative is:

 class ContactElement extends StatelessWidget {
   late IconData _icon;
   late  String _heading;
   late String _describer;

  ContactElement( {required IconData icon, required String heading, describer}) {
    _icon = icon;
    _heading = heading;
    _describer = describer;
  }
}
Related