Flutter 使用GlobalKey从另一个类更改颤振状态

Flutter 使用GlobalKey从另一个类更改颤振状态,flutter,flutter-layout,Flutter,Flutter Layout,我有一张底片,上面有可以换的孩子。我试图使用GlobalKey从子对象访问父对象的方法。它引发以下异常: The following NoSuchMethodError was thrown while handling a gesture: The method 'selectedChild' was called on null. Receiver: null Tried calling: selectedChild(1) 我只是想改变另一个类的状态。任何建议都很好。我怎样才能让它工作 家

我有一张底片,上面有可以换的孩子。我试图使用
GlobalKey
从子对象访问父对象的方法。它引发以下异常:

The following NoSuchMethodError was thrown while handling a gesture:
The method 'selectedChild' was called on null.
Receiver: null
Tried calling: selectedChild(1)
我只是想改变另一个类的状态。任何建议都很好。我怎样才能让它工作

家长:

class\u ServicesModal扩展StatefulWidget{
@凌驾
ServicesModelState createState()=>ServicesModelState();
}
类ServicesModelState扩展了状态{
var selectedChild=0;
变量_子项=[
ServicePackage(),
调用()
];
选择儿童(整数选择){
设置状态(){
selectedChild=select;
});
}
@凌驾
小部件构建(构建上下文){
返回容器(
装饰:盒子装饰(
颜色:颜色,白色,
borderRadius:仅限borderRadius(
左上:半径。圆形(20),
右上角:半径。圆形(20),
)
),
孩子:ClipRRect(
borderRadius:仅限borderRadius(
左上:半径。圆形(20),
右上角:半径。圆形(20),
),
child:_children[selectedChild]
),
);
}
}
子项:

class ServicePackage扩展StatefulWidget{
GlobalKey _serviceModalState=GlobalKey();
@凌驾
_ServicePackageState createState()=>\u ServicePackageState();
}
类_ServicePackageState扩展状态{
@凌驾
小部件构建(构建上下文){
返回容器(
孩子:我的钮扣(
图标:图标(Icons.add),
已按下:(){
设置状态(){
widget.\u serviceModalState.currentState.selectedChild(1);
});
},
),
);
}
}

您在
\u ServicePackageState
类中将
selectChildren
误输入为
selectedChild

检查此答案可能会有所帮助