In Isolates, I can refer to a local variable from an outer scope or a field variable of a class without passing it as a separate message.
Is this implicitly copying the values into the new isolation's memory area?
I'm curious about the details.

示例

class Person {
  Person(this._baseNum);

  /// access [_baseNum] in isolate
  final int _baseNum;
  int age = 0;

  /// access [extraAge] in isolate
  Future<void> addAge(int extraAge) async {
    final mainReceivePort = ReceivePort();

    await Isolate.spawn((SendPort sendPort) async {
      sendPort.send(await _calcAge(_baseNum, extraAge));
    }, mainReceivePort.sendPort);

    age = await mainReceivePort.first;
    mainReceivePort.close();
  }

  static Future<int> _calcAge(int someNum, int age) async {
    // ... heavy work ...
    return age + someNum;
  }
}

// ...

void main() {
  test('test', () async {
    final p = Person(10);
    await p.addAge(3);
    expect(p.age, 13);
  });
}

推荐答案

在隔离中,我可以引用外部作用域中的局部变量或类的字段变量,而无需将其作为单独的消息传递.

这是否隐式地将值复制到新隔离的内存区?

是的.

演示这一点的一种方法是,从外部作用域或字段变量中获取这些变量之一,并更新隔离内的值.您将看到的是,从隔离外部,该值不会被更新.这是因为他们使用的是变量的独立副本.

import 'dart:isolate';
import 'package:test/test.dart';

class Person {
  Person(this._baseNum);

  /// access [_baseNum] in isolate
  int _baseNum;
  int age = 0;

  /// access [extraAge] in isolate
  Future<void> addAge(int extraAge) async {
    final mainReceivePort = ReceivePort();

    await Isolate.spawn((SendPort sendPort) async {
      _baseNum++; // modify _baseNum
      sendPort.send(await _calcAge(_baseNum, extraAge));
    }, mainReceivePort.sendPort);

    age = await mainReceivePort.first;
    mainReceivePort.close();
  }

  static Future<int> _calcAge(int someNum, int age) async {
    // ... heavy work ...
    return age + someNum;
  }
}

// ...

void main() {
  test('test', () async {
    final p = Person(10);
    await p.addAge(3);
    expect(p.age, 14);
    expect(p._baseNum, 10); // _baseNum still 10 despite _baseNum++ in isolate
  });
}

Flutter相关问答推荐

我遇到了一个问题,从showDialogue()调用Navigator.pop()两次导致屏幕空白

如何更新文本字段的基础上的选定下拉菜单?

如何在Ffltter Chrome应用程序中使用webview_fltter_web显示自定义html而不是外部uri?

如何在2024年使用Ffltter将用户数据保存在云FireStore中?

出现异常.RangeError(RangeError(index):无效值:有效值范围为空:0).分度误差

如何将assets资源 实体类型转换为文件类型?

BottomNavigationBar-我应该使用Container和Align吗?

将记录/元组用作SplayTreeMap中的键

使用现有Map方法对子类克隆方法的逻辑进行Dart标准化

如何在 Flutter 中创建具有渐变背景色的自定义 Snackbar?

如何在flutter中将所有单词的第一个字母大写

Flutter ListView 在调用 setState 后未更新

Flutter firebase_auth 和 firebase_core 依赖错误

Flutter / 为什么当我点击我的图片时我的模型没有更新?

为什么 ref.watch(otherProvider.stream) 在 Riverpod 2.x 中被弃用并且将在 3.x 中被删除?

改变步进器的线条 colored颜色 Flutter

TextSpan 避免符号字符串组上的换行符

我收到这个错误我无法解决

如何将图像网络装箱到具有边界半径的容器中

在 Flutter 应用程序中全局使用 assets 文件夹