【问题标题】:Flutter change state from another class using GlobalKeyFlutter 使用 GlobalKey 从另一个类更改状态
【发布时间】: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);
         });
        },
      ),
    );
  }
}

【问题讨论】:

标签: flutter flutter-layout


【解决方案1】:

您在 _ServicePackageState 类中将 selectChildren 错误地输入为 selectedChild

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2018-08-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    相关资源
    最近更新 更多