Search code examples
dartfinal

static final object changes identity


I have a browser application written in Dart. I noticed a strange error appearing where my StageXL ResourceManager was missing the resources that it previously had. After debugging the program for a while I ended up with this situation:

In global.dart:

class Global {
    static final ResourceManager resourceManager = new ResourceManager();
}

In main function:

var resources = Global.resourceManager;
resources.addBitmapData("Player", "images/player_base.png");
await resources.load();
print("in main: ${identityHashCode(Global.resourceManager)} = "
    " ${Global.resourceManager.resources}, isolate: ${identityHashCode(
    Isolate.current)}");

In another function where I need to access the resource afterwards:

print("elsewhere: ${identityHashCode(Global.resourceManager)} = "
    " ${Global.resourceManager.resources}, isolate: ${identityHashCode(
    Isolate.current)}");

Expected output (identityHashCodes match and so do the object contents):

in main: 12345678 = [ResourceManagerResource [kind=BitmapData, name=Player, 
    url = images/player_base.png]], isolate: 09876543
elsewhere: 12345678 = [ResourceManagerResource [kind=BitmapData, 
    name=Player, url = images/player_base.png]], isolate: 09876543

Actual output (note the identityHashCode mismatch):

in main: 516570559 = [ResourceManagerResource 
    [kind=BitmapData, name=Player, url = images/player_base.png]],
    isolate: 843028171
elsewhere: 419835243 = [], isolate: 843028171

I thought this may have something to do with running in a different isolate (not familiar with them) but as you can see, the current isolates identityHashCodes match.


Solution

  • That is surprising. My best guess is that you are importing the same library twice, using different URIs. The fact that one of your files is a "main" file supports this, since its a common mistake to specify the main file on the command line as a file and have it import a package library using a relative reference.

    Is your "main" file in a package lib directory, and does it import the resource file using a relative path? If so, try changing that import to a package:packageName/thepath URI instead and see if it changes anything.

    (My personal recommendation is to never have a Dart library URL that contains lib, whether in an import/export or on the command line. Always use a package: URI in that case instead.)