flutter - 如何从另一个 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()
但没有成功。任何解决此问题的帮助将不胜感激。
解决方案
您可以使用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();
}
}
推荐阅读
- android - SearchView 样式扰乱了 Toolbar Style Actionbar
- c# - C#:从包含“use master”的数据库生成 SQL 脚本
- amazon-ec2 - 使用 Vagrant 在现有 aws e2 实例上部署 yii2 高级应用程序
- perl - 在 Perl 中将散列数组转换为标量值数组
- c# - 无法将模型绑定到 DevExpress 按钮的路由值
- excel - 需要 VBA 才能在所有选项卡上工作
- c++ - 是否可以从字符串访问变量?
- node.js - 在 docker 容器内创建的目录未反映在主机上
- c++ - 将 unicode 替换为 C++ 字符串中的空格时出现分段错误错误
- python - 获取两个文本文件中的唯一行