user-interface - Flutter UI 卡在异步操作上

标签 user-interface asynchronous flutter

如何正确构造以下代码?我启动了一个昂贵的异步操作。 “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,
            )
          ],
        ),
      ),
    );
  }
}

最佳答案

class _MyHomePageState extends State<MyHomePage> {

  void _pressed() async {
    print("I am pressed");
    print("I will make a cheap operation now");

    // string returned is "Good Morning"
    String string = await compute(runExpensiveOperation, null); // this is what you need
  }

  @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,
            )
          ],
        ),
      ),
    );
  }
}

// make sure this is outside your class definition 
Future<String> runExpensiveOperation(void _) 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');
  return "Good Morning";
}

关于user-interface - Flutter UI 卡在异步操作上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56758816/

相关文章:

java - 如何在Struts 2中使项目国际化?

node.js - 一起使用 Promise 和 async

javascript - Redux Thunk 用于简单的异步请求

没有 app Bar 的 Flutter IphoneX 状态栏颜色

flutter - 不透明度值的更改未反射(reflect)在应用程序中

Java 数独 GUI 板

c# - 透明背景显示黑色

Java swing - ActionListener 应该去哪里?

swift - 异步调用全部成功或者都不成功,如何处理

android - 即使安装了应用程序,Firebase 动态链接也会重定向到 Playstore