我在玩Flutter 打中的蛇游戏,但我有个问题.我正在改变我在GameTick方法中的蛇形位置(蛇形变量)--工作得很好,然后我在Build方法(网格变量)中生成新的网格--工作得很好,最后Build方法应该返回窗口小部件树.但我在屏幕上看不到变化.看起来构建方法正在使用旧的网格变量构建应用程序.
我删除了一些无关的代码.谢谢你的帮助.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:swipe/swipe.dart';
void main() {
runApp(
MaterialApp(
title: 'snake',
theme: ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.blueGrey,
),
home: Game(),
),
);
}
class Game extends StatefulWidget {
const Game({Key? key}) : super(key: key);
@override
State<Game> createState() => _GameState();
}
class _GameState extends State<Game> {
List<List<int>> snake = [
[5, 5],
[6, 5],
[7, 5]
];
List<Container> grid = List.filled(121, Container());
Timer? timer;
@override
void initState() {
Timer.periodic(Duration(seconds: 1), (Timer t) => gameTick());
super.initState();
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
void gameTick() {
for (List<int> pair in snake) {
setState(
() {
pair[0]--;
},
);
}
}
@override
Widget build(BuildContext context) {
for (int i = 0; i < 121; i++) {
int row = (i / 11).floor();
int col = i % 11;
for (List<int> pair in snake) {
int snakeRow = pair[0];
int snakeCol = pair[1];
if ((snakeRow == row) && (snakeCol == col)) {
grid[i] = Container(
decoration: BoxDecoration(
color: Colors.greenAccent,
border: Border.all(color: Color(0xFF383434), width: 2),
),
);
break;
} else {
grid[i] = Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.greenAccent, width: 2),
),
);
}
}
}
return Scaffold(
body: SizedBox.expand(
child: Swipe(
onSwipeUp: () {SOMECODE});
}
},
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: GridView.count(
physics: NeverScrollableScrollPhysics(),
crossAxisCount: 11,
children: grid,
),
),
],
),
),
),
);
}
}