我使用的是fluter_google_places Flutter插件。我正在尝试将一个回调函数传递到小部件中,这样当点击一个位置时,就会调用该回调函数:
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
}
}
}
在另一个文件中创建小部件:
void myCallback() {
// ...
}
GooglePlaces(myCallback);
但是,回调显示错误:没有为类“PlacesAutocompleteWidget”定义方法“widget.callback();
”
如何从小部件调用回调函数?
发布于 2019-02-28 03:13:10
你遇到这个错误是因为class _GooglePlacesState extends PlacesAutocompleteState
而不是State<GooglePlaces>
。所以widget.callback()
指的是PlacesAutocompleteWidget
的状态。
这里有两个解决方案:
1)便宜的出路:
将回调传递给状态,如下所示:_GooglePlaces createState() => _GooglePlacesState(callback);
并将回调添加到状态构造函数。
2) (如上所述)修改_GooglePlacesState
以扩展State<GooglePlaces>
。
https://stackoverflow.com/questions/54917491
复制相似问题