我正在学习Flutter / Dart,特别是如何在画布上绘画。
我想使用FOR循环绘制多条线。我希望在迭代之间有一个延迟,这样我才能看到每一行都一个接一个地绘制。
参考这两篇文章:
异步编程:期货https://www.dartlang.org/tutorials/language/futures
异步编程:流 https://www.dartlang.org/tutorials/language/streams
我能够编写一个“文本版本”线条画,以显示我可以延迟正在运行的FOR循环并打印一些文本。
// print 10 lines 'text version'
Future printTenLines() async {
for (int z = 0; z <= 9; z++) {
await addDelay();
print('Line $z');
}
}
main() {
printTenLines();
}
const delayTime = Duration(milliseconds: 1000);
Future addDelay() => Future.delayed(delayTime);
但是当我将实际的canvas.drawLine()函数替换为'text version'print()例程时,会出现异常错误。
const delayTime = Duration(milliseconds: 10);
Future<String> addDelay() => Future.delayed(delayTime);
// draw 10 lines on the canvas
Future<void> drawTenLines() async {
for (double i = 0; i <= 100; i += 10) {
await addDelay();
print('Line $i');
canvas.drawLine(
Offset(size.width/2, size.height/2),
Offset(i, 0),
paint,
);
}
drawTenLines();
我发现此问题类似于尝试打印两个嵌套循环的输出。执行代码,并在外部循环完成时打印两个循环的输出。
我尝试了嵌套循环来绘制线条,外层循环来绘制线条,而内层循环则充当延迟计时器。程序等待,直到两个循环都完成,并且所有线条都被立即绘制。
使用这个异步Futures和Streams的示例是我最接近达到预期结果的示例。
“文本版本”行式打印机已延迟并且可以正常使用。但是该延迟不适用于canvas.drawLine()。这是我完整的代码。它按原样工作并绘制10条线。取消注释延迟调用以查看异常。我只希望画布在绘制下一行之前延迟一定的时间。
`
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Drawing Lines",
home: DrawingPage(),
);
}
}
class DrawingPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Draw Ten Lines"),
),
body: CustomPaint(
painter: LinePainter(),
child: Center(
child: Text(
"",
style: TextStyle(fontSize: 20, fontStyle: FontStyle.italic),
),
),
));
}
}
class LinePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint();
paint.color = Colors.blue;
paint.strokeWidth = 1;
paint.style = PaintingStyle.stroke;
const delayTime = Duration(milliseconds: 1000);
Future<void> addDelay() => Future.delayed(delayTime);
Future<void> drawTenLines() async {
for (double i = 0; i <= 100; i += 10) {
//await addDelay();
print('Line $i');
canvas.drawLine(
Offset(size.width / 2, size.height / 2),
Offset(i, 0),
paint,
);
//await addDelay();
}
}
drawTenLines();
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
`
答案 0 :(得分:1)
尝试这种方式。
Future.delayed(const Duration(milliseconds: 500), () {
// Here you can write your code
setState(() {
// Here you can write your code for open new view
});
});
第二种方法..二手计时器
Timer _timer;
_timer = new Timer(const Duration(milliseconds: 400), () {
setState(() {
// Here you can write your code for open new view
});
});
定时器导入'dart:async'