Search code examples
setstateplaying-cards

Why setState could not restate the widget class


I have written the code for card game trying to show the cards using the Playing card library and, having created the show player hand in the widget class, it could show the cards in a good orders at static stage. However, when I tried to deal card and add additional card to the List (i.e. hand), and setState, it was not update the screening accordingly. Can anyone help?

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Games _game = Games();
  int _counter = 0;
  List<Kar> desk = [];
  List<Kar> remainingDesk = [];
  Kar _drawnCard;
  double _avgCounter = 0;
  ShapeBorder shape = RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(8),
      side: BorderSide(color: Colors.black, width: 1));
  List<Kar> _playerA = [
    Kar(suit: 1, rank: 14),
    Kar(suit: 1, rank: 11),
  ];
  List<Kar> _dealer = [
    Kar(suit: 2, rank: 12),
    Kar(suit: 3, rank: 13),
  ];
  List<Kar> _blackJack = [
    Kar(suit: 1, rank: 14),
    Kar(suit: 1, rank: 11),
    Kar(suit: 3, rank: 13),
  ];
  double _cardSize = 0;
  bool _selected = false;
  bool _second = false;
  bool _playerTurn = false;
  bool _dealerTurn = false;
  bool _playerTurnEnd = false;
  bool _dealerTurnEnd = false;
  int _handScore = 0;

  @override
  void initState() {
    Games _games = Games();
    setState(() {
      desk = createDesk();
      remainingDesk = List.from(desk);
    });
    _incrementCounter();
    super.initState();
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Container(
          width: 300,
          height: 580,
          child: Stack(
            children: [
              PlayerHand(player: false, hand: _playerA),
              Text('Score: ' + _handScore.toString()),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: () {
            Kar _drawnCard = drawCardfromDesk(remainingDesk);
              setState(() {
                _handScore += _drawnCard.rank;
                _playerA.add(_drawnCard);

              });
            });
          },
               tooltip: 'Increment',
          child: Icon(Icons
              .add)), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  List<Kar> createDesk() {
    List<Kar> desk = [];
    for (int _rank = 2; _rank < 15; _rank++) {
      for (int _suit = 1; _suit < 5; _suit++) {
        desk.add(Kar(suit: _suit, rank: _rank));
      }
      ;
    }
    ;
    return desk;
  }

  Kar drawCardfromDesk(List<Kar> desk) {
    Kar _dealCard;
    var rng = new Random();
    _dealCard = desk[rng.nextInt(desk.length)];
    desk.remove(_dealCard);
    return _dealCard;
  }
}


import 'dart:convert';

import 'dart:io';

import 'package:blackjack/main.dart';
import 'package:flutter/material.dart';
import 'package:playing_cards/playing_cards.dart';


class PlayerHand extends StatefulWidget {
  List<Kar> hand;
  bool player= false;
  BuildContext context;


  PlayerHand({
    @required this.hand,
    @required this.player
  });

  @override
  _PlayerHandState createState() => _PlayerHandState();
}

class _PlayerHandState extends State<PlayerHand> {
  int _handLength=0;
  bool _player= false;
  ShapeBorder shape = RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(8),
      side: BorderSide(color: Colors.black, width: 1));




@override
  void initState() {
    //var authBloc = Provider.of<AuthBloc>(context);
    // TODO: implement initState
    setState(() {
      _handLength = widget.hand.length;
      _player = widget.player;
    });
    

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    //final authBloc = Provider.of<AuthBloc>(context);
    

    return _handLength==0
    ?Container()
    : _handLength ==1
    ? Container(
        child: PlayingCardView(
          card: PlayingCard(
              suitsName[widget.hand[0].suit], cardValue[widget.hand[0].rank]),
          showBack: false,
          shape: shape,
        ),
      )
    : _handLength ==2
    ? Container(
      child:Container(
                  height: 180,
                  width: 380,
                 // duration: Duration(seconds: 1),
                  child: FlatCardFan(children: [
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[0].suit],
                            cardValue[widget.hand[0].rank]),
                        showBack: _player?true:false,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[1].suit],
                            cardValue[widget.hand[1].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                  ]))
    )
    : _handLength ==3
    ? Container(
      child:Container(
                  height: 180,
                  width: 380,
                  //duration: Duration(seconds: 1),
                  child: FlatCardFan(children: [
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[0].suit],
                            cardValue[widget.hand[0].rank]),
                        showBack: _player?true:false,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[1].suit],
                            cardValue[widget.hand[1].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                        PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[2].suit],
                            cardValue[widget.hand[2].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                  ]))
    ): _handLength ==4
    ? Container(
      child:Container(
                  height: 180,
                  width: 300,
                 // duration: Duration(seconds: 1),
                  child: FlatCardFan(children: [
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[0].suit],
                            cardValue[widget.hand[0].rank]),
                        showBack: _player?true:false,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[1].suit],
                            cardValue[widget.hand[1].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[2].suit],
                            cardValue[widget.hand[2].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[3].suit],
                            cardValue[widget.hand[3].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                  ]))
    ): _handLength ==5
    ? Container(
      child:AnimatedContainer(
                  height: 180,
                  width: 300,
                  duration: Duration(seconds: 1),
                  child: FlatCardFan(children: [
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[0].suit],
                            cardValue[widget.hand[0].rank]),
                        showBack: _player?true:false,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[1].suit],
                            cardValue[widget.hand[1].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[2].suit],
                            cardValue[widget.hand[2].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[3].suit],
                            cardValue[widget.hand[3].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                      PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[4].suit],
                            cardValue[widget.hand[4].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                  ]))
    ) : _handLength ==6
    ?Container(
      child:AnimatedContainer(
                  height: 180,
                  width: 300,
                  duration: Duration(seconds: 1),
                  child: FlatCardFan(children: [
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[0].suit],
                            cardValue[widget.hand[0].rank]),
                        showBack: _player?true:false,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[1].suit],
                            cardValue[widget.hand[1].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[2].suit],
                            cardValue[widget.hand[2].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[3].suit],
                            cardValue[widget.hand[3].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                      PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[4].suit],
                            cardValue[widget.hand[4].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                      PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[5].suit],
                            cardValue[widget.hand[5].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                  ]))
    )
    : Container(
      child:AnimatedContainer(
                  height: 180,
                  width: 300,
                  duration: Duration(seconds: 1),
                  child: FlatCardFan(children: [
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[0].suit],
                            cardValue[widget.hand[0].rank]),
                        showBack: _player?true:false,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[1].suit],
                            cardValue[widget.hand[1].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[2].suit],
                            cardValue[widget.hand[2].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[3].suit],
                            cardValue[widget.hand[3].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                      PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[4].suit],
                            cardValue[widget.hand[4].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                      PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[5].suit],
                            cardValue[widget.hand[5].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                        PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[6].suit],
                            cardValue[widget.hand[6].rank]),
                        //showBack: true,
                        elevation: 3.0,
                        shape: shape),
                  ])));

  }


}

Solution

  • Build your widget dynamically :

    FlatCardFan( 
               children: List.generate(widget.hand.length, (index) =>  
                    PlayingCardView(
                        card: PlayingCard(suitsName[widget.hand[index].suit],
                            cardValue[widget.hand[0].rank]),
                        showBack: _player?true:false,
                        elevation: 3.0,
                        shape: shape
                       ),
                    ),
                 ), 
    

    Let me know if this works for you.