how to assign values to global variables in a function and use them in other functions in dart

Issue

I tried to declare variable in dart in this way but it shows a warning due to null safety.

double latitude; 
double longitude;

Again I tried like this but the values did not assign to the variables latitude and longitude in the function varcheck().

double? latitude;
double? longitude;
void varcheck(){
  latitude=33;
  longitude=44;
}
void main() {
  print(latitude);
  print(longitude);
}

Output
null
null

how to assign the values to the global variables in a function and use them in any other functions

Solution

try below code hope its help to you. just call your varcheck() inside main main method

double? latitude;
double? longitude;
void varcheck() {
  latitude = 33;
  longitude = 44;
}

void main() {
  varcheck();
  print(latitude);
  print(longitude);
}

Your result->
33
44

Answered By – Ravindra S. Patil

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *