Reputation: 285
I have two callback functions in a stateful widget which are called by two different screens. Here is the how I declared them in the stateful widget(onChange and finalBetList);
class AppListView extends StatefulWidget {
final ValueChanged onChange;
final List<MatchList> matchList;
final ValueChanged finalBetList;
AppListView({this.onChange, this.matchList, this.finalBetList});
And this is how I implemented them in the state class of the widget. Even if I try to pass the same parameter onChange working perfectly but finalBetList getting this error. The method 'call' was called on null.Receiver: null Tried calling: call(1)
widget.onChange(counter);
widget.finalBetList(counter);
Everything is same, one of them is workiing but other one get the error. What I'm missing?
Edit
This is the code where I call my stateful widget from HomeScreen(which works perfect)
Stack(children: [
AppListView(
matchList: matchList,
//callback function brings the counter value from ListView class
onChange: (value) {
setState(() {
counter = value;
});
},
),
This is the code where I call my stateful widget from second secreen(which gets error)
body: Container(
child: AppListView(
onChange: (value) {},
finalBetList: (value) {
counter = value;
setState(() {
//counter = value;
});
},
matchList: matchList),
),
Upvotes: 0
Views: 2334
Reputation: 1073
TL;DR
Assign an empty body implemention to the finalBetList
property
Stack(children: [
AppListView(
matchList: matchList,
finalBetList: (value) {}, // <- NEW CODE IS HERE
//callback function brings the counter value from ListView class
onChange: (value) {
setState(() {
counter = value;
});
},
),
Why should you do it?
In Dart, functions are objects. Objects, if not assigned a value, are null
. In the code example from HomeScreen
you assign a value to onChange
, so later when you call it through widget.onChange(counter)
, onChange
is evaluated as a function object and its body is executed.
However, in the same example you don't assign any value to finalBetList
so it's left as null
. When you make the call widget.finalBetList(counter)
, finalBetList
is evaluated and it's clearly not a function object. At this point you'd except an error, but it's not the end of the story - as not only function objects can be called. Any class that implements the call()
method can be called, too. So a call to finalBetList.call()
is attempted. This is the exception you should get:
NoSuchMethodError: The method 'call' was called on null.
Receiver: null
Obviously null
doesn't implement a call()
method so it doesn't exists and an exception is thrown.
If you don't want to assign an empty body implemention to the finalBetList
property inside HomeScreen
, you also have the option to assign it in the constructor.
Another option I can think of is calling the function using conditional member access:
widget.finalBetList?.call(counter);
All function objects have the call()
method which executes the function's body.
Upvotes: 3