我有一个底页,它的子级可以更改。我正在尝试使用GlobalKey
从孩子那里访问父母的方法。它在下面引发异常:
The following NoSuchMethodError was thrown while handling a gesture:
The method 'selectedChild' was called on null.
Receiver: null
Tried calling: selectedChild(1)
我只是想从另一个类更改状态。任何建议都很好。我该如何运作?
父母:
class _ServicesModal extends StatefulWidget {
@override
ServicesModalState createState() => ServicesModalState();
}
class ServicesModalState extends State<_ServicesModal> {
var selectedChild = 0;
var _children = [
ServicePackage(),
Calls()
];
selectChildren(int select) {
setState(() {
selectedChild = select;
});
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
)
),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
child: _children[selectedChild]
),
);
}
}
孩子:
class ServicePackage extends StatefulWidget {
GlobalKey<ServicesModalState> _serviceModalState = GlobalKey();
@override
_ServicePackageState createState() => _ServicePackageState();
}
class _ServicePackageState extends State<ServicePackage> {
@override
Widget build(BuildContext context) {
return Container(
child: IconButton(
icon: Icon(Icons.add),
onPressed: () {
setState(() {
widget._serviceModalState.currentState.selectedChild(1);
});
},
),
);
}
}
答案 0 :(得分:0)
您在selectChildren
类中将selectedChild
输入为_ServicePackageState
。