Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

android - Flip all cards when click a button using flip_card flutter

Solved see the answers

I am using flip card package to make flip cards.
I have many cards in the same page and I want to flip them all when I press a button.
I used the example in the documentation :

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

but I get error Duplicate GlobalKey detected in widget tree. or Multiple widgets used the same GlobalKey
So what I can do to solve this problem ?

question from:https://stackoverflow.com/questions/65901637/flip-all-cards-when-click-a-button-using-flip-card-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved this problem with making a map of global keys
var cardKeys = Map<int, GlobalKey<FlipCardState>>();
and in the ListView.builder in itemBuilder I added

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

and in the FlipCard I added key: thisCard

Then I make a simple for loop in the button onPressed function

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

Thanks to this answer here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...