Search code examples
flutterdartoopdart-null-safety

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

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