我试图在另一个名为SwipeButton的onDragEnd函数中从Map类的Map类调用一个函数(addGeoPoint),这两个函数都是有状态的。
class Map extends StatefulWidget {
//Some Code
_MapState createState() => _MapState();
}
class _MapState extends State<Map> {
//Some Functions
void addGeoPoint() async{
}
文件2
class SwipeButton extends StatefulWidget {
// Some Code
@override
SwipeButtonState createState() => SwipeButtonState();
}
class SwipeButtonState extends State<SwipeButton>
with SingleTickerProviderStateMixin {
// Some functions
void _onDragEnd(DragEndDetails details) {
// I want to call the addGeoPoint() function here
}
}
为此,我尝试将Map类的实例创建为Map mapScreen = new Map
,然后使用mapScreen.addGeoPoint()
访问该函数,但是没有成功。解决该问题的任何帮助将不胜感激。
答案 0 :(得分:0)
您可以使用VoidCallBacks在小部件之间进行通信:
地图:
class Map extends StatefulWidget {
//Some Code
_MapState createState() => _MapState();
}
class _MapState extends State<Map> {
//Some Functions
void addGeoPoint() async{
//do things
}
Widget buildSwipeButton() {
...
...
return SwipeButton(
onAddGeoPoint: addGeoPoint,
);
}
SwipeButton:
class SwipeButton extends StatefulWidget {
final VoidCallback onAddGeopoint;
SwipeButton({this.onAddGeoPoint});
// Some Code
@override
SwipeButtonState createState() => SwipeButtonState();
}
class SwipeButtonState extends State<SwipeButton>
with SingleTickerProviderStateMixin {
// Some functions
void _onDragEnd(DragEndDetails details) {
// I want to call the addGeoPoint() function here
widget.onAddGeoPoint();
}
}
答案 1 :(得分:0)
您可以这样声明小部件
class YourWidget extends StatefulWidget {
final Function callback;
YourWidget({@required this.textButton});
@override
YourWidgetState createState() => YourWidgetState();
}
然后您可以在有状态的父级中传递这样的功能
YourWidget(
callback: (){}
)
ant,然后您就可以在YourWidget中像在其他小部件或其他功能中一样使用
widget.callback()