【发布时间】:2019-11-07 13:46:09
【问题描述】:
如何正确构造以下代码?我启动了一个昂贵的异步操作。 “runExpensiveOperation”方法停止旋转的 CircularProgressIndicator,因此它似乎是在主线程上执行的。有没有像原生 iOS 上的“dispatch_async”之类的东西?
class _MyHomePageState extends State<MyHomePage> {
void _pressed() async {
print("I am pressed");
print("I will make a cheap operation now");
await runExpensiveOperation();
}
Future<void> runExpensiveOperation() async {
print('starting expensive operation');
for (var i = 0; i<1000000; i++) {
List<int> bytes = utf8.encode('somethingtohash');
String hash = sha256.convert(bytes).toString();
}
print('finished expensive operation');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
FlatButton(
child: Text("Press me for tough operation"),
onPressed: _pressed,
)
],
),
),
);
}
}
【问题讨论】:
-
你可以在这种情况下使用 Isolates
标签: user-interface asynchronous flutter