skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. You can define a global variable outside the ‘Location‘ widget as a ‘currentPosition‘,

    class Position {
      static String? currentPosition;
    }

    call from ‘Location‘ this variable and set it.

    class MyApp extends StatefulWidget {
      const MyApp({super.key});
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      @override
      void initState() {
        Position.currentPosition = 'currentPosition';
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: TextButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: ((context) => LocationWidget()),
                  ),
                );
              },
              child: Text('Click Me'),
            ),
          ),
        );
      }
    }

    Then call it again from ‘WeatherApi‘ and use it.

    class WeatherWidget extends StatefulWidget {
      const WeatherWidget({super.key});
    
      @override
      State<WeatherWidget> createState() => _WeatherWidgetState();
    }
    
    class _WeatherWidgetState extends State<WeatherWidget> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Text(Position.currentPosition ?? 'null'),
          ),
        );
      }
    }
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search