Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing function as default value of an optional parameter

I’m trying to pass a function as default value of an optional parameter, but it gives me the followig error "The default value of an optional parameter must be constant"

class ElevatedBtn extends StatelessWidget {
  final String text;
  final color, width, height, onTap;
  
  const ElevatedBtn(
    {super.key, required this.text, this.color, this.width, this.height, this.onTap=(){} }
   );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Default value of positional parameters are needed to be const. You can make onTap nullable and call your method on null case like

class ElevatedBtn extends StatelessWidget {
  final String text;
  final color, width, height;
  final VoidCallback? onTap;

  const ElevatedBtn({
    super.key,
    required this.text,
    this.color,
    this.width,
    this.height,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onTap ?? () {},
      child: Text("btn"),
    );
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading