如何重建有状态的小部件?

时间:2020-05-25 21:08:05

标签: flutter dart setstate

我有一个叫做Square(chess)的有状态小部件。我在它的各种属性上调用setstate,但是除非执行热重载,否则它不会在屏幕上更新。

class Square extends StatefulWidget {
  Square({
    this.address,
    this.piece,
    this.color,
    this.onPressed,
    this.selected = false,
  });
  String address;
  Piece piece;
  Color color;
  Function onPressed;
  bool selected;

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

class _SquareState extends State<Square> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child:
          RawMaterialButton(onPressed: widget.onPressed, child: widget.piece),
      color: widget.selected == true ? kSelectedSquareColor : widget.color,
    );
  }
}

在同一文件中,我经历了繁重的过程,手动创建64,将这64个文件编译成8个8的列表,然后将它们传递给名为board的列表。这是正方形对象的示例:

Square(address: 'A8', piece: blackRook, color: kWhiteSquares)

然后,我创建一个网格:

class _ChessBoardState extends State<ChessBoard> {
  List<List> board = startingSetup;
  bool turn = true;
  Square selected;
  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 5,
      child: GridView.count(
        crossAxisCount: 8,
        children: List.generate(
          64,
          (index) {
            Square square = board[index ~/ 8][index % 8];
            square.onPressed = () {
              if (selected == null) {
                // shorter for you
              } else if (square == selected) {
                // shorter for you
              } else {
                print('three');
                setState(() {
                  selected.selected = false;
                  Piece p = selected.piece;
                  square.piece = p;
                  selected.piece = null;
                  selected = null;
                });
              }
            };
            return square;
          },
        ),
      ),
    );
  }
}

为了您的理智,我省略了if和else if。所有条件均有效,但仅在我重新加载后才在屏幕上显示。为什么在调用setState时窗口小部件不能自动重建?例如,在square.piece上调用setState并添加新片段时,应该不应该吗?

0 个答案:

没有答案