4

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

  • 5
    `final IconData _icon; final String _heading; final String _describer; ContactElement({IconData icon, String heading, String describer}) : _icon = icon, _heading = heading, _describer = describer;` – pskink Oct 03 '21 at 05:35
  • 1
    @pskink This should be the answer. –  Oct 03 '21 at 06:21
  • 2
    so write a self answer then ;-) – pskink Oct 03 '21 at 06:22

3 Answers3

9

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;
barracus
  • 368
  • 5
  • 15
  • This needs to extend the super class `super()` of `StatelessWidget` ([Dart explanation](https://dart.dev/guides/language/language-tour#extending-a-class), look at my answer – Guillem Puche Mar 09 '22 at 16:38
4

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;
  ...
}
Guillem Puche
  • 1,199
  • 13
  • 16
-1

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