简体   繁体   中英

Flutter change state from another class using GlobalKey

I have a Bottom Sheet and it has children that can be changed. I'm trying to use GlobalKey to access the parent's methods from the child. It throws an exception below:

The following NoSuchMethodError was thrown while handling a gesture:
The method 'selectedChild' was called on null.
Receiver: null
Tried calling: selectedChild(1)

I'm just trying to change the state from another class. Any suggestions would be great. How can I make it work?

Parent:

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

Child:

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

您在_ServicePackageState类中将_ServicePackageState错误selectChildrenselectedChild

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM