【问题标题】:What is the context/scope of Flutter's compute functionFlutter 的计算功能的上下文/范围是什么
【发布时间】:2019-02-05 19:57:54
【问题描述】:

我正在学习 Flutter 的 compute 函数。我对它的理解是,它是为了将繁重的计算工作卸载到另一个线程,以免阻塞 UI 线程。我遇到了一些我不太了解的行为。考虑下面的应用程序。

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

void main() => runApp(new MyApp());

class StringValues {
  static String foo = 'Foo';
  static String bar;
}

String _calculate(String value) {
  return value + ' ' + (StringValues.foo ?? 'undefined') + ' ' + (StringValues.bar ?? 'undefined');
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  void _testCompute() async {
    String result1 = _calculate('values are:');
    String result2 = await compute(_calculate, 'values are:');

    StringValues.bar = 'Bar';

    String result3 = _calculate('values are:');
    String result4 = await compute(_calculate, 'values are:');

    print(result1);
    print(result2);
    print(result3);
    print(result4);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _testCompute,
        child: new Icon(Icons.print),
      ),
    );
  }
}

_testCompute 函数的输出是:

values are: Foo undefined
values are: Foo undefined
values are: Foo Bar
values are: Foo undefined

它编译得很好。我希望result4result3 相同。谁能解释为什么不是?如here 所述,我还尝试了使用“全局变量”的不同方法,但结果是相同的。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    compute() 创建一个新的隔离。 以这种方式开始的隔离区除了代码之外什么都不共享。
    就像您将使用_calculate 作为入口点而不是main 来启动一个具有相同项目的新进程一样。

    compute 使用 SendPort/ReceivePort 组合将'values are:' 传递给isolate,然后在隔离开始运行时将该值作为参数传递给_calculate

    值是按值传递的,因此传递对象引用并在另一端更改它不会对发送方产生任何影响。

    再一次,隔离不共享状态,只有代码,它们使用SendPort/ReceivePort 在主隔离和“compute”隔离之间来回传递值。

    【讨论】:

      猜你喜欢
      • 2014-09-30
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2020-11-15
      • 2010-10-22
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多