【发布时间】:2020-05-18 18:44:30
【问题描述】:
我有一个底页,它有可以更改的子项。我正在尝试使用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);
});
},
),
);
}
}
【问题讨论】:
-
检查这个答案可能会有所帮助stackoverflow.com/a/56928670/10660823