I'm using VoidCallback to call setState from child widget. But the callback function is not executing at all.
Below is my code in essence.
Child Widget:
class TextFormMentorHashtag extends StatefulWidget {
const TextFormMentorHashtag({Key? key, required this.callback}) : super(key: key);
final VoidCallback callback;
@override
_TextFormMentorHashtagState createState() =>
_TextFormMentorHashtagState();
}
class _TextFormMentorHashtagState extends State<TextFormMentorHashtag> {
@override
Widget build(BuildContext context) {
...
TextFormField(
...
onChanged: (value) {
if(_formKey.currentState!.validate()) {
...
print('call callback');
widget.callback;
}
}
)
}
}
parent widget:
class ApplyMentorPage extends StatefulWidget {
const ApplyMentorPage({Key? key}) : super(key: key);
@override
State<ApplyMentorPage> createState() => _ApplyMentorPageState();
}
class _ApplyMentorPageState extends State<ApplyMentorPage> {
...
bool _disabled = true;
@override
Widget build(BuildContext context) {
void callback() {
print('callback called');
setState(() {
_disabled = !_mentorProvider.check();
});
}
return Scaffold(
...
child: Column(
children: [
TextFormMentorHashtag(callback: callback),
...
// _disabled turns submit button on and off in the later code
When I run code and press child widget terminal prints 'call callback' but no 'callback called'. What am I missing?
CodePudding user response:
If your using TextFormField it has also ontap on it
TextFormField(
onTap: () {
print("am called");
}
)
so you will is maybe like this
TextFormField(
onTap: widget.calback
)
CodePudding user response:
You didn't call callback
in your _TextFormMentorHashtagState
. You should call it like widget.callback()
or widget.callback.invoke()
.
Full code:
class _TextFormMentorHashtagState extends State<TextFormMentorHashtag> {
@override
Widget build(BuildContext context) {
...
TextFormField(
...
onChanged: (value) {
if(_formKey.currentState!.validate()) {
...
print('call callback');
// or widget.callback()
widget.callback.invoke();
}
}
)
}
}