Home > Enterprise >  How to set default value of function in a constructor (Flutter)
How to set default value of function in a constructor (Flutter)

Time:11-01

I want to set default function in my child Widget in a constructor.

Basically, I have two widgets

  1. Login (Parent Widget)
  2. AppButton (Child Widget)

Here is my AppButton.dart

AppButton.dart

And I am calling this child widget in Login.dart (Parent) like this:

AppButton(title: "Login")

Please give me a way that to set default function without making "onPress" required for it's Parent (Login.dart)

TIA

CodePudding user response:

Only static value can be set as default value in constructor, so you need define you function as static like this:

class AppButton extends StatefulWidget {
  final Function onPress;
  const AppButton({Key? key, this.onPress = _onPress}) : super(key: key);
  
  static void _onPress(){}

  @override
  State<AppButton> createState() => _AppButtonState();
}

CodePudding user response:

just make it nullable:

 class MyButton extends StatefulWidget {
  final void Function()? onPress;
  final String title;
  const MyButton({Key? key, this.onPress, required this.title}) : super(key: key);

  @override
  State<MyButton> createState() => _MyButtonState();
}

class _MyButtonState extends State<MyButton> {

  void Function() defaultOnPress = (){
    // your default function here
  };

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(onPressed: widget.onPress ?? defaultOnPress, child: const Text("my button"));
  }
}

still you can get const constructor

  • Related