I wanted to some singleton class and implemented. I referred this article https://stackoverflow.com/a/12649574/6323093 .
My implementation is like this. All source files are same lib
directory.
Singleton.dart
class Singleton {
static final instance = Singleton();
int value = 0;
}
user1.dart
import 'singleton.dart'; // non-package expression
int getValue1() {
return Singleton.instance.value;
}
setValue1(int val) {
Singleton.instance.value = val;
}
user2.dart
import 'package:singleton/singleton.dart'; // package expression
int getValue2() {
return Singleton.instance.value;
}
setValue2(int val) {
Singleton.instance.value = val;
}
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()) // -> 99
print(getValue2()) // -> 999
In above code, I expected getValue1()
and getValue2()
are both 999
but actual results are 99
and 999
.
When I change user2.dart
's import statement to import 'singleton.dart
or user1.dart
's import statement to 'package:singleton/singleton.dart';
, results are 999
(as I expected).
Is this correct Dart's behavior? Or this behavior is bug?
I'm confusing because I thought both import expressions, package and non-package, are exact same meaning.