我已经使用资产图像构建了骰子掷骰动画,但是该图像最后仅更新一次,但是使用循环生成了6次随机骰子数。
import 'package:dicee/dice_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
return runApp(
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChangeNotifierProvider<DiceModel>(
child: DicePage(),
create: (BuildContext context) => DiceModel(),
)),
);
}
class DicePage extends StatelessWidget {
void updateDices(DiceModel dice) {
for (int i = 0; i < 6; i++) {
print(i);
sleep(Duration(milliseconds: 1000));
dice.generateDiceOne();
}
}
@override
Widget build(BuildContext context) {
List<String> _diceOneImages = [
"images/dice1.png",
"images/dice2.png",
"images/dice3.png",
"images/dice4.png",
"images/dice5.png",
"images/dice6.png",
];
final dice = Provider.of<DiceModel>(context);
final c = dice.diceOneCount;
var img = Image.asset(
_diceOneImages[c - 1],
gaplessPlayback: true,
);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: GestureDetector(
onTap: () => updateDices(dice),
child: img,
),
),
],
),
],
);
}
}```
**DiceModel**
```import 'dart:math';
import 'package:flutter/foundation.dart';
class DiceModel with ChangeNotifier {
int diceOne = 1;
int get diceOneCount => diceOne;
void generateDiceOne() {
diceOne = Random().nextInt(5) + 1;
print("diceOne: $diceOne");
notifyListeners();
}
}```
答案 0 :(得分:1)
问题是您正在呼叫sleep(Duration(milliseconds: 1000));
。如果您检查日志,则应该得到UnsupportedError
以及消息"This embedder disallows calling dart:io's sleep()"
。该功能仅在主/ UI隔离之外的隔离(Dart线程)上起作用。因此,下一行代码dice.generateDiceOne();
永远不会执行。
改为使updateDices
异步,并将sleep
替换为await Future.delayed(const Duration(seconds: 1));
。