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/