【发布时间】:2021-03-27 08:03:30
【问题描述】:
上下文
我正在开发一个按时间顺序执行某些操作的函数,我希望能够暂停其执行,然后在按下按钮时恢复。
问题
使用下面的代码,当代码到达await Future.doWhile(() => _isTestPaused); 时,UI 会冻结
代码
import 'package:flutter/material.dart';
class Sample extends StatefulWidget {
const Sample();
@override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> {
String _text;
bool _isTestPaused;
@override
void initState() {
_text = '';
_isTestPaused = false;
WidgetsBinding.instance.addPostFrameCallback((_) => _run());
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Expanded(child: Text(_text)),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _isTestPaused = !_isTestPaused),
child: Icon(_isTestPaused ? Icons.play_arrow : Icons.pause),
),
);
}
Future<void> _run() async {
int count = 0;
for (int i = 0; i < 100; i++) {
await Future.delayed(const Duration(seconds: 1));
await Future.doWhile(() => _isTestPaused);
setState(() => _text += '${count += 1}\n');
}
}
}
【问题讨论】:
标签: android flutter user-interface dart async-await