Flutter UI挂起异步操作

时间:2019-06-25 16:58:37

标签: 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,
            )
          ],
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

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 
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";
}