gpt4 book ai didi

flutter - Flutter中的setState()方法直到for循环中的最后一次调用才更新 View

转载 作者:行者123 更新时间:2023-12-03 03:01:14 25 4
gpt4 key购买 nike

问题

我正在尝试使用Flutter构建排序可视化程序。我使用了CustomPainter来绘制与要排序的整数列表的值相对应的垂直线。
设置该应用程序,以便当用户单击DropDownButton中的“气泡排序”选项时
(我打算稍后再添加更多的排序算法)CustomPainter的Canvas中的垂直线必须对其进行排序。


import 'dart:io';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() => runApp(HomePage());

class HomePage extends StatefulWidget {
@override
HomePageSate createState() {
return HomePageState();
}
}

class HomePageState extends State<HomePage> {
List<int> arr;

@override
void initState() {
super.initState();
arr = _getRandomIntegerList();
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Sorting Visualiser'),
actions: <Widget>[
DropdownButton<String>(
onChanged: (dynamic choice) {
switch (choice) {
case 'Bubble Sort':
_bubbleSortVisualiser();
break;
}
},
items: <String>['Bubble Sort']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
)
],
),
//The following flatButton refreshes arr to have a new array of random integers.
bottomNavigationBar: FlatButton(
onPressed: () {
setState(() {
arr = _getRandomIntegerList();
});
},
child: Icon(Icons.refresh),
),
body: CustomPaint(
size: Size(double.infinity, double.infinity),
painter: SortingCanvas(arr),
),
),
);
}

//function to sort the list using bubble sort and repaint the canvas at every iteration.
void _bubbleSortVisualiser() {
print('Bubble sort function called');
List<int> bubbleArr = List.from(arr);

for (int i = 0; i < bubbleArr.length - 1; i++) {
for (int j = 0; j < bubbleArr.length - 1 - i; j++) {
int temp;
if (bubbleArr[j] < bubbleArr[j + 1]) {
temp = bubbleArr[j];
bubbleArr[j] = bubbleArr[j + 1];
bubbleArr[j + 1] = temp;
//Every time arr changes setState() is called to visualise the changing array.
setState(() {
arr = List.from(bubbleArr);
print("Updated to : $arr");
});

//Sleep is called so that the change is noticeable
sleep(Duration(seconds: 1));

}
}
}
}
}

class SortingCanvas extends CustomPainter {
List<int> arr;

SortingCanvas(this.arr);

@override
void paint(Canvas canvas, Size size) {
var linePaint = Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 5.0
..isAntiAlias = true;
//IMP the first offset is the bottom point and the second is the top point of the vertical line.
//It is offset from the top left corner of the canvas
for (int i = 1; i <= arr.length; i++) {
canvas.drawLine(Offset(50.0 + (20 * i), size.height - 50),
Offset(50.0 + (20 * i), 50.0 * arr[i - 1]), linePaint);
}
}

@override
bool shouldRepaint(SortingCanvas oldDelegate) {
return !listEquals(this.arr, oldDelegate.arr);
}
}

//Helper function to get a list of 10 random integers
List<int> _getRandomIntegerList() {
List<int> arr = [];
Random rng = new Random();

for (int i = 0; i < 10; i++) {
arr.add(rng.nextInt(10));
}
return arr;
}

但是,最终发生的结果是,在 Canvas 上仅可视化了最终排序的 arr,并且出于某种原因跳过了所有中间步骤。但是日志显示列表正在更新。

屏幕截图

带有随机列表的初始屏幕

单击下拉按钮中的气泡排序

排序 list

添加 sleep()函数只是为了模拟动画,解决此问题后,我打算将其替换为适当的动画。另外,我知道该应用程序有点笨拙,但是我想在完善UI之前弄清楚逻辑。

最佳答案

尝试像这样使用Future.delay

      void _bubbleSortVisualiser() async {
print('Bubble sort function called');
List<int> bubbleArr = List.from(arr);

for (int i = 0; i < bubbleArr.length - 1; i++) {
for (int j = 0; j < bubbleArr.length - 1 - i; j++) {
int temp;
if (bubbleArr[j] < bubbleArr[j + 1]) {
temp = bubbleArr[j];
bubbleArr[j] = bubbleArr[j + 1];
bubbleArr[j + 1] = temp;
//Every time arr changes setState() is called to visualise the changing array.
await Future.delayed(const Duration(seconds: 1), () {
setState(() {
arr = List.from(bubbleArr);
print("Updated to : $arr");
});
});




}
}
}
}
}

关于flutter - Flutter中的setState()方法直到for循环中的最后一次调用才更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59236853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com