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

时间:2020-02-03 00:50:31

标签: 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)

我只是想从另一个类更改状态。任何建议都很好。我该如何运作?

父母:

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

1 个答案:

答案 0 :(得分:0)

您在selectChildren类中将selectedChild输入为_ServicePackageState