I have started learning Dart and Flutter and wanted to understand one concept:
Updated code: try in dartpad
class Service{
String ask = '';
void write (String receivedData){
ask = receivedData;
}
}
class WriteNow{
String hi = 'hi';
Service art = Service();
void okay () {
art.write(hi);
}
}
void main () {
WriteNow a = WriteNow();
a.okay();
Service b = Service();
print(b.ask);
}
I run WriteToService first and then ReadFromService, I cannot get the 'Hello', but get the original string ''. Please clarify. Also, how does this scale?
Solution 1: user14596272
class Service {
String ask = '';
void write (String receivedData){
ask = receivedData;
}
}
class WriteToService{
Service a = Service();
a.write('hello');
}
class ReadFromService {
Service b = Service();
print(b.ask);
}
What you are Doing:
Step 1: The Service class contains String ask = '';
Step 2: Running WriteToService
class
Step 3: Running ReadFromService
class
So ReadFromService
class displays original String content which is ask = ''
as it has been reassigned to String ask = ''
. Scope of the previous entry hi
of WriteToService
class was ended.
Correct way to do it:
void main() {
WriteToService ok1 = new WriteToService();
ReadFromService ok2 = new ReadFromService();
}
String globelVariable = 'hi';
class Service {
String ask = globelVariable;
void write(String receivedData) {
globelVariable = receivedData;
}
}
class WriteToService {
Service a = new Service();
WriteToService() {
String name = "hello";
a.write(name);
}
}
class ReadFromService {
Service b = new Service();
ReadFromService() {
print(b.ask1);
}
}
Now declare a global variable String globelVariable = 'hi';
and assign it to String ask = globelVariable;
in class Service
. In write
method assign the receiving data to global variable globelVariable = receivedData;
. Since the scope of global variable doesn't end till the program is terminated it won't loose the value of the string hello
which is eventually printed when ReadFromService
class is called.
Test the above code at https://dartpad.dev/
Solution 2: Ademir Villena Zevallos
You are creating different instances of the Service
class, that's the reason you can't get the updated String. Let me explain, in this piece of code:
WriteNow a = WriteNow();
a.okay();
You are creating an instance of the Service
class, called art
. The art
instance has its member called ask
, which is empty. When you call a.okay()
, you are modifying the ask
member of the art
instance. So now, if you run this print(a.art.ask)
you will get the 'hi'
response.
Instead of that, you are creating another instance of the Service
class, called b
, and then you are printing the b.ask
value. Can you see the error? You modified the art
instance, not the b
instance.
The ask
value is not "global" to all the instances of the Service
class, each instance has its own ask
value, and each instance can change it without modifying the other instances.