dart 异常:迭代期间并发修改:'_GrowableList'的示例(长度:17)

cetgtptt  于 2023-11-14  发布在  其他
关注(0)|答案(6)|浏览(144)

我做了一个游戏,在//ERROR ZONE中被称为异常,我不明白。类游戏有List重排序。

  1. void spawnt(){
  2. var rnd = new Random();
  3. var rnd2 = new Random();
  4. rnd = rnd.nextInt(100);
  5. if(rnd2.nextBool())
  6. rnd2 = rnd2.nextInt(100);
  7. else
  8. rnd2 = -rnd2.nextInt(100);
  9. var x = flappy.position["x"]+lastx+sw+rnd;
  10. var y = rnd2*pomer-100-1800*pomer-168*pomer;
  11. Rectangle vrch = new Rectangle("img/tube1.png", sw, sh, {"x":x, "y":y, "z":0});
  12. Rectangle spodek = new Rectangle("img/tube2.png", sw, sh, {"x":x, "y":sh+mezeray*pomer+y, "z":0});
  13. vrch.onCollision((_){
  14. checkover();
  15. });
  16. spodek.onCollision((_){
  17. checkover();
  18. });
  19. game.addObject(spodek);
  20. game.addObject(vrch);
  21. var cp = new Checkpoint(sw, mezeray, {"x":x+sw, "y":y+sh, "z":0});
  22. cp.onCollision((e){
  23. scoore++;
  24. querySelector("#scoore").text="SCOORE: ${scoore}";
  25. sounds[1].play();
  26. //THIS IS ERROR ZONE
  27. spawnt();
  28. });
  29. game.addObject(cp);
  30. rnd = new Random();
  31. rnd = rnd.nextInt(300);
  32. rnd2 = new Random();
  33. rnd2 = rnd2.nextInt(300);
  34. var rnd3 = new Random();
  35. rnd3 = new Random();
  36. rnd3 = rnd3.nextInt(10);
  37. Grab w;
  38. if(rnd3 == 0 || rnd3 == 1 || rnd3 == 2){
  39. w = new Grab("img/cigarette.png", 600*pomer, 418*pomer, {"x":x+sw+rnd,"y":sh+mezeray*pomer+y-mezeray*pomer+rnd2-168*pomer, "z":0});
  40. w.scale(0.2);
  41. w.onCollision((c){
  42. smokescreen = true;
  43. smoketimer.cancel();
  44. smoketimer = new Timer(const Duration(milliseconds: 10000), (){
  45. smokescreen = false;
  46. });
  47. kucky.play();
  48. if(csong)
  49. cig.play();
  50. csong = false;
  51. });
  52. game.addObject(w);
  53. }
  54. else if(rnd3 == 3 || rnd3 == 4){
  55. w = new Grab("img/whiskey.png", 162*pomer, 398*pomer, {"x":x+sw+rnd,"y":sh+mezeray*pomer+y-mezeray*pomer+rnd2-168*pomer, "z":0});
  56. w.scale(0.2);
  57. w.onCollision((c){
  58. AudioElement pr = new AudioElement("sounds/yes.${koncovka}");
  59. pr.play();
  60. whiskey++;
  61. if(whiskey>=10 && whiskey<20){
  62. speedotoceni = 30;
  63. zhoupni();
  64. }
  65. else if(whiskey>=20 && whiskey<30){
  66. speedotoceni = 25;
  67. zhoupni();
  68. }
  69. else if(whiskey>=30 && whiskey<40){
  70. speedotoceni = 20;
  71. zhoupni();
  72. }
  73. else if(whiskey>=40 && whiskey<50){
  74. speedotoceni = 15;
  75. zhoupni();
  76. }
  77. else if(whiskey>=50 && whiskey<60){
  78. speedotoceni = 10;
  79. zhoupni();
  80. }
  81. else if(whiskey>=60 && whiskey<70){
  82. speedotoceni = 5;
  83. zhoupni();
  84. }
  85. else if(whiskey>=70 && whiskey<80){
  86. speedotoceni = 1;
  87. zhoupni();
  88. }
  89. querySelector("#scoore").text="SCOORE: ${scoore}";
  90. });
  91. game.addObject(w);
  92. }
  93. else if(rnd3 == 9){
  94. w = new Grab("img/jatra.png", 539*pomer, 521*pomer, {"x":x+sw+rnd,"y":sh+mezeray*pomer+y-mezeray*pomer+rnd2-168*pomer, "z":0});
  95. w.scale(0.1);
  96. w.onCollision((c){
  97. AudioElement pr = new AudioElement("sounds/yes.${koncovka}");
  98. pr.play();
  99. jatra++;
  100. document.cookie = "jatra=${jatra}; expires=Thu, 24 Dec 4000 00:00:00 GMT; path=/";
  101. querySelector("#jatracount").text = jatra.toString();
  102. });
  103. game.addObject(w);
  104. }
  105. lastx = lastx+300*pomer+rnd;
  106. }

字符串
class Game.dart

  1. import 'dart:html';
  2. import 'dart:math';
  3. import 'dart:async';
  4. import 'Entity.dart';
  5. import 'Gravity.dart';
  6. import 'Rectangle.dart';
  7. import 'Camera.dart';
  8. import 'Checkpoint.dart';
  9. class Game {
  10. CanvasElement canvas;
  11. Gravity gravity;
  12. List<Entity> entities = new List();
  13. List<Rectangle> rectangles = new List();
  14. Camera camera;
  15. var leftSpace = 0;
  16. var topSpace = 0;
  17. var _onCollision;
  18. var _over = (_){};
  19. var _render = (_){};
  20. num _lastFrame = 0;
  21. bool isOver = false;
  22. Game(this.canvas, this.gravity){
  23. window.animationFrame.then((e){this.render(e);});
  24. }
  25. void addEntity(Entity entita){
  26. this.entities.add(entita);
  27. }
  28. void addObject(Rectangle rectangle){
  29. this.rectangles.add(rectangle);
  30. }
  31. void render(num delta){
  32. num fps = 1000/(delta-this._lastFrame);
  33. this._lastFrame = delta;
  34. CanvasRenderingContext2D ctx = this.canvas.context2D;
  35. ctx.clearRect(0, 0, this.canvas.width+this.leftSpace.abs(), this.canvas.height+this.topSpace.abs());
  36. this._render(true);
  37. this.rectangles.forEach((s){
  38. ctx.fillStyle=s.color;
  39. if(s.hasColor()){
  40. ctx.fillStyle=s.color;
  41. ctx.fillRect(s.position["x"]-this.leftSpace,s.position["y"]-this.topSpace,s.width,s.height);
  42. }
  43. else{
  44. ctx.drawImageScaled(s.texture, s.position["x"]-this.leftSpace,s.position["y"]-this.topSpace,s.width,s.height);
  45. }
  46. });
  47. this.entities.forEach((e){
  48. e.move(fps);
  49. e.power["y"] += this.gravity.operate(e)*(60/fps);
  50. ctx.save();
  51. ctx.translate(e.position["x"]-this.leftSpace+e.width/2, e.position["y"]-this.topSpace+e.height/2);
  52. ctx.rotate(e.rotation* PI/180);
  53. ctx.drawImageScaled(e.img, -(e.width/2), -(e.height/2), e.width, e.height);
  54. ctx.restore();
  55. });
  56. collisionResponse();
  57. checkCollisions();
  58. if(!this.camera.fixed["x"])
  59. this.leftSpace = this.camera.target.position["x"]-this.canvas.width/2+this.camera.target.width/2;
  60. else
  61. this.leftSpace = this.camera.fixedPos["x"];
  62. if(!this.camera.fixed["y"])
  63. this.topSpace = this.camera.target.position["y"]-this.canvas.height/2+this.camera.target.height/2;
  64. else
  65. this.topSpace = this.camera.fixedPos["y"];
  66. this._render(false);
  67. ctx.closePath();
  68. window.animationFrame.then((e){this.render(e);});
  69. }
  70. void onCollision(e){
  71. this._onCollision = e;
  72. }
  73. void collisionResponse(){
  74. this.rectangles.forEach((s){
  75. num x1 = s.position["x"];
  76. num y1 = s.position["y"];
  77. num z1 = s.position["z"];
  78. num w1 = s.width;
  79. num h1 = s.height;
  80. this.entities.forEach((e){
  81. num rot = e.rotation * (PI / 180);
  82. num x2 = e.position["x"];
  83. num y2 = e.position["y"];
  84. num z2 = e.position["z"];
  85. num w2 = e.width;
  86. num h2 = e.height;
  87. if(x2>=x1-w2 && x2<=x1+w1 && y2>y1-h2 && y2<y1+h1 && z1==z2){
  88. s.collisionResponse(e);
  89. e.collision(s);
  90. s.collision(e);
  91. }
  92. });
  93. });
  94. }
  95. void checkCollisions(){
  96. List<Entity> kolize = new List();
  97. for(Entity e1 in this.entities){
  98. num x1 = e1.position["x"];
  99. num y1 = e1.position["y"];
  100. num z1 = e1.position["z"];
  101. num w1 = e1.width;
  102. num h1 = e1.height;
  103. for(Entity e2 in this.entities){
  104. if(e1 == e2 || (kolize.indexOf(e1) != -1 && kolize.indexOf(e2) != -1)) continue;
  105. num x2 = e2.position["x"];
  106. num y2 = e2.position["y"];
  107. num z2 = e2.position["z"];
  108. num w2 = e2.width;
  109. num h2 = e2.height;
  110. if(x2>=x1-w2 && x2<=x1+w1 && y2>y1-h2 && y2<y1+h1 && z1==z2){
  111. kolize.add(e1);
  112. kolize.add(e2);
  113. }
  114. }
  115. }
  116. }
  117. void over(){
  118. if(!this.isOver)
  119. this._over();
  120. this.isOver = true;
  121. }
  122. void onOver(e){
  123. this._over = e;
  124. }
  125. void onRender(f){
  126. this._render = f;
  127. }
  128. }


未捕获错误:在迭代过程中并发修改:'_GrowableList'的Instance(length:17). Stack Trace:#0 List.forEach(dart:core-patch/growable_array.dart:241)

1 Game.collisionResponse(FlappyBird/web/classes/Game.dart:83:28)

2 Game.render(FlappyBird/web/classes/Game.dart:62:22)

3 Game.render.(FlappyBird/web/classes/Game.dart:75:47)

4 _rootRunUnary(dart:zeroc/zone.dart:717)

5 _RootZone.runUnary(dart:zh/zone.dart:854)

6 _Future._propagateToListeners. PropagateValueCallback(dart:future_impl.dart:439)

7 _Future._propagateToListeners(dart:future_impl.dart:522)

8 _Future._complete(dart:future_impl.dart:303)

9 _SyncCompleter.complete(dart:future_impl.dart:44)

10 Window. animationFrame.(file:/E:/B/build/slave/dartium-win-full-stable/build/src/build/Release/obj/global_intermediate/blink/bindings/dart/dart/html/Window.dart:62)

异常:迭代期间并发修改:'_GrowableList'的示例(长度:17). undefined(undefined:0:0)
够了吗?有人知道怎么修理吗?谢谢回答。:)

wlp8pajw

wlp8pajw1#

此错误意味着您在迭代过程中正在向集合中添加或从集合中移除对象。这是不允许的,因为添加或移除项将更改集合大小并扰乱后续迭代。
错误可能来自以下行之一,您尚未发布其源代码:

  1. s.collisionResponse(e);
  2. e.collision(s);
  3. s.collision(e);

字符串
我假设其中一个调用是在forEach期间从实体列表或矩形列表中删除一个项,这是不允许的。相反,您必须重新构造代码以删除列表迭代之外的项,可能使用removeWhere方法。
考虑以下从列表中删除奇数的尝试:

  1. var list = [1, 2, 3, 4, 5];
  2. list.forEach( (e) {
  3. if(e % 2 == 1)
  4. list.remove(e);
  5. });


这将失败,并出现并发修改异常,因为我们试图在列表迭代期间删除这些项。
然而,在列表迭代期间,我们可以标记要删除的项,然后使用removeWhere在批量操作中删除它们:

  1. var list = [1, 2, 3, 4, 5];
  2. var toRemove = [];
  3. list.forEach( (e) {
  4. if(e % 2 == 1)
  5. toRemove.add(e);
  6. });
  7. list.removeWhere( (e) => toRemove.contains(e));

展开查看全部
6za6bjd0

6za6bjd02#

来自https://api.dartlang.org/stable/2.1.0/dart-core/Map/removeWhere.html的最新Dart版本2.1.0的新文档
执行

  1. var map = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5};
  2. // delete the map entry that has the key 'a'
  3. map.removeWhere((key, value) => key == 'a');

字符串

w1e3prcc

w1e3prcc3#

尽量避免循环列表太多。使用这个:

  1. list.removeWhere((element) => element % 2 == 1;

字符串

y53ybaqx

y53ybaqx4#

这样你就可以从动态列表中删除对象,并且在迭代过程中不会遇到异常并发修改,因为循环是由removeWhere自己完成的!

  1. List data = [
  2. {
  3. "name":"stack"
  4. },
  5. {
  6. "name":"overflow"
  7. }
  8. ];
  9. data.removeWhere((item) => item["name"]=="stack");
  10. print(data);

字符串
输出

  1. [{name: overflow}]

展开查看全部
mm5n2pyu

mm5n2pyu5#

创建列表的副本并修改我有一个stockQty列表,但我想修改也将在某些条件下中断,所以我不能使用关于answers.so我做了一个列表的副本,并在它上面循环并修改差异。

  1. var stockQty = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
  2. var purchaseQty = 15;
  3. var stockQrtCp = stockQty.toList();
  4. for (int sq in stockQrtCp) {
  5. if (purchaseQty >= sq) {
  6. print('Purchase Qty is greater than Stock Qty');
  7. stockQty.removeWhere((element) => element == sq);
  8. purchaseQty = purchaseQty - sq;
  9. } else {
  10. print('Purchase Qty is less than Stock Qty');
  11. sq = sq - purchaseQty;
  12. if (sq == 0) {
  13. stockQty.removeWhere((element) => element == sq);
  14. }
  15. break;
  16. }
  17. }

字符串

展开查看全部
w8rqjzmb

w8rqjzmb6#

有点明显,但如果你有点累了,它可能不会那么明显:仔细检查你的函数的参数与Widget的变量之一不相似。
在我的例子中:

  1. class _ManageUsersPageState extends State<ManageUsersPage> {
  2. late List<User> users;
  3. ...
  4. void removeUser(List<User> users) { // worked after renaming the param to 'removedUsers'. this is the code before fixing the issue.
  5. List<User> tmp = users;
  6. for (User user in removedUsers) { // also made the change here, this is the code after renaming from 'users' to 'removedUsers' and fixing the issue.
  7. tmp.removeWhere((User item) => item.id == user.id);
  8. }
  9. setState(() => users = tmp);
  10. }
  11. }

字符串

展开查看全部

相关问题