小编kai*_*osk的帖子

Dart 单例中的奇怪行为

我想要一些单例类并实现。我参考了这篇文章/sf/answers/885470211/

我的实现是这样的。所有源文件都在同一个lib目录下。

单身人士.dart

class Singleton {
    static final instance = Singleton();
    int value = 0;
}
Run Code Online (Sandbox Code Playgroud)

用户1.dart

import 'singleton.dart'; // non-package expression

int getValue1() {
    return Singleton.instance.value;
}

setValue1(int val) {
  Singleton.instance.value = val;
}
Run Code Online (Sandbox Code Playgroud)

user2.dart

import 'package:singleton/singleton.dart'; // package expression

int getValue2() {
    return Singleton.instance.value;
}

setValue2(int val) {
  Singleton.instance.value = val;
}
Run Code Online (Sandbox Code Playgroud)

main.dart

import 'user1.dart';
import 'user2.dart';

// below is test code
setValue1(99)
setValue2(999)
// My expected behavior is both '999'... why??
print(getValue1()) // …
Run Code Online (Sandbox Code Playgroud)

dart

2
推荐指数
1
解决办法
468
查看次数

标签 统计

dart ×1