I have a statfull class called ‘Location’ which get the location with Geolocatar and Im showing the location with this :
Text(currentPosition!=null? '$currentPosition' : '----',),
and this is :
static Position? currentPosition;
and I have another class called ‘WeatherApi’ which Im using Openweathermap Api to get the weather . now I want to use the currentPosition in the api url
https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid={API key}
how can I use the currentPosition in the url? I have tried widget.variablename but didn’t work
3
Answers
You can pass the location details through the constructor of the WeatherApi class. Create a final variable(currentPosition) in the WeatherApi class and make it as required and when you navigate from Location screen to WeatherApi screen, in the
Navigator.push(context, //your route => WeatherApi(currentPosition: currentPosition));
and to use the variable, do widget.currentPosition in the WeatherApi class
Check out this for more info
You can define a global variable outside the ‘
Location
‘ widget as a ‘currentPosition
‘,call from ‘
Location
‘ this variable and set it.Then call it again from ‘
WeatherApi
‘ and use it.In Flutter, one way to pass a variable from one class to another is
Using a constructor: You can pass the variable as a parameter in the constructor of the class that needs the variable.
you can read the details in the official documentation