Home > Software engineering >  Passing function as default value of an optional parameter
Passing function as default value of an optional parameter

Time:10-02

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

CodePudding user response:

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"),
    );
  }
}
  • Related