首页 > 解决方案 > 如何从另一个 StatefulWidget 调用 StatefulWidget 中的函数?

问题描述

我试图在另一个名为 onDragEnd 的 SwipeButton 类的函数中从 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()但没有成功。任何解决此问题的帮助将不胜感激。

标签: flutterdart

解决方案


您可以使用VoidCallBacks在 Widgets 之间进行通信:

地图:

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,
    );
}

滑动按钮:

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();
}

}

推荐阅读