首页 > 解决方案 > 使用 Flip_card 颤动单击按钮时翻转所有卡片

问题描述

解决了看答案

我正在使用翻转卡包制作翻转卡。
我在同一页上有很多卡片,我想在按下按钮时将它们全部翻转。
我使用了文档中的示例:

GlobalKey<FlipCardState> cardKey = GlobalKey<FlipCardState>();

@override
Widget build(BuildContext context) {
  return FlipCard(
    key: cardKey,
    flipOnTouch: false,
    front: Container(
      child: RaisedButton(
        onPressed: () => cardKey.currentState.toggleCard(),
        child: Text('Toggle'),
      ),
    ),
    back: Container(
      child: Text('Back'),
    ),
  );
}

但我得到错误Duplicate GlobalKey detected in widget tree.或者Multiple widgets used the same GlobalKey
我能做些什么来解决这个问题?

标签: androidiosflutterflutter-layoutflutter-dependencies

解决方案


我通过制作全局键映射解决了这个问题,
var cardKeys = Map<int, GlobalKey<FlipCardState>>();
并在其中ListView.builder添加itemBuilder

cardKeys.putIfAbsent(index, () => GlobalKey<FlipCardState>());
GlobalKey<FlipCardState> thisCard = cardKeys[index];

并在FlipCard我添加key: thisCard

然后我在按钮 onPressed 函数中做了一个简单的 for 循环

              RaisedButton(
                onPressed: () {
                  for (int i = 0; i < names.length; i++) {
                    cardKeys[i].currentState.toggleCard();
                  }
                },
                child: Text('Toggle'),
              ),

感谢这里的答案


推荐阅读