[英]Passing variable to Flutter widget that extends another class
I am using the fluter_google_places Flutter plugin. 我正在使用fluter_google_places Flutter插件。 I am trying to pass a callback function into the widget, such that when a Place is tapped, the callback function is called: 我正在尝试将回调函数传递到小部件中,以便在点击位置时调用该回调函数:
class GooglePlaces extends PlacesAutocompleteWidget {
final Function callback;
GooglePlaces(this.callback)
: super(
apiKey: kGoogleApiKey,
sessionToken: Uuid().generateV4(),
language: "en",
);
@override
_GooglePlaces createState() => _GooglePlacesState();
}
class _GooglePlacesState extends PlacesAutocompleteState {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
void startSearch() async {
Prediction p = await PlacesAutocomplete.show(
context: context,
apiKey: kGoogleApiKey,
mode: Mode.overlay,
language: "en",
);
displayPrediction(p);
}
Future<Null> displayPrediction(Prediction p) async {
if (p != null) {
widget.callback(); // Call callback function
}
}
}
Creating the widget in another file: 在另一个文件中创建窗口小部件:
void myCallback() {
// ...
}
GooglePlaces(myCallback);
However the widget.callback();
但是widget.callback();
displays the error: The method 'callback' isn't defined for the class 'PlacesAutocompleteWidget' 显示错误:未为类“ PlacesAutocompleteWidget”定义“回调”方法
How do I call the callback function from the widget? 如何从窗口小部件调用回调函数?
You're running into this error because class _GooglePlacesState extends PlacesAutocompleteState
not State<GooglePlaces>
. 您正在class _GooglePlacesState extends PlacesAutocompleteState
此错误,因为class _GooglePlacesState extends PlacesAutocompleteState
而不是State<GooglePlaces>
。 So widget.callback()
refers to a state of PlacesAutocompleteWidget
. 因此, widget.callback()
指向PlacesAutocompleteWidget
的状态。
There's two solutions here: 这里有两种解决方案:
1) The cheap way out: 1)便宜的出路:
Pass the callback to the state like so: _GooglePlaces createState() => _GooglePlacesState(callback);
像这样将回调传递到状态: _GooglePlaces createState() => _GooglePlacesState(callback);
and add the callback to the state constructor. 并将回调添加到状态构造函数。
2) (As stated above) Change _GooglePlacesState
to extend State<GooglePlaces>
. 2)(如上所述),更改_GooglePlacesState
扩展State<GooglePlaces>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.