I want to set default function in my child Widget in a constructor.
Basically, I have two widgets
- Login (Parent Widget)
- AppButton (Child Widget)
Here is my 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