2

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.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
kainosk
  • 23
  • 4

2 Answers2

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

is likely the culprit.

Relative import in lib/main.dart are know to cause such issues.

Change them to

import 'package:my_flutter_project/user1.dart';
import 'package:my_flutter_project/user2.dart';

and it should work as expected.

Relative imports are fine in other files.

The related Dart issue is https://github.com/dart-lang/sdk/issues/33076 A fix should be work in progress.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Thank you for your answer! Now I understand this behavior is not my fault. I'll keep watching this issue. – kainosk Sep 26 '18 at 15:24
-1

I had the same issue when spelling the imports wrong:

import 'backend/backend.dart';
import 'backend/Backend.dart';

Turns out that they both deliver different instances (!)

Rudolf J
  • 517
  • 4
  • 10