Rafay Mustafa
Rafay Mustafa

Reputation: 119

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

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

Upvotes: 0

Views: 1125

Answers (3)

Ahmed Sherif
Ahmed Sherif

Reputation: 1

you could put "static" before childOnPress()

Upvotes: 0

Sayyid J
Sayyid J

Reputation: 1573

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

Upvotes: 2

eamirho3ein
eamirho3ein

Reputation: 17950

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

Upvotes: 4

Related Questions