Is it safe to use global variable to share objects between functions in Dart?

Issue

I see that “Dart is a single-threaded programming language”, so I think is it safe to use global variable to pass data between functions:

var g = 1;

main() {
   hello();
   world();
}

def hello() {
    g = 2;
}

def world() {
    print(g);
}

I also see that “Dart provides isolates” and which can run on multi-cores. That means it may be dangerous if different isolates visit the same global variable, right?

Is it safe? And if not, is there any way to share objects between functions without passing them as parameters?


Update:

Per “Florian Loitsch”‘s answer, I just wrote a testing for the global variable with isolates:

import 'dart:isolate';

var g = 1;

echo() {
  port.receive((msg, reply) {
    reply.send('I received: $g');
  });
}

main() {
  var sendPort = spawnFunction(echo);

  void test() {
    g = 2;
    sendPort.call('Hello from main').then((reply) {
      print("I'm $g");
      print(reply);
      test();
    });
  }
  test();
}

You can see one isolate will set the global variable g to a new value, and another isolate will print the value of g.

The console it prints:

I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1

It’s clear that they don’t share memory, and global variable is safe.

Solution

Dart is single-threaded within one thread. It is hence safe (though bad style) to pass data in global variables.

Isolates have their separate heaps (memory) and don’t interfere with each other. Global variables stay safe.

I don’t think there is a way to pass variables between functions except for static variables and parameters.

Answered By – Florian Loitsch

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.