How to pass values into API Flutter?

I want to hit a Geo location Api with Latitude,Longtitude and key values.
Api- “https://api.opencagedata.com/geocode/v1/json?q=LAT+LNG&key=YOUR-API-KEY

I have tried like this,

static final String location_url =
      "https://api.opencagedata.com/geocode/v1/json?q=LAT+LNG&key=YOUR-API-KEY";
  var getLocationUrl =
      location_url + '?q=' + _Latitude + '+' + _Longtitude + '&key' + apikey;
  Future<String> getLocation() async {
    var res = await http.get(
      Uri.parse(getLocationUrl),
      headers: {
        "Content-type": "application/json",
        "Accept": "application/json"
      },
    );
    var getLocationResponse = json.decode(res.body);
    print(getLocationResponse);
    print(res.statusCode);
    print(res.body);
  }

I got error as,

Error: Can't access 'this' in a field initializer to read '_Latitude'.
      location_url + '?q=' + _Latitude + '+' + _Longtitude + '&key' + apikey;
                             ^^^^^^^^^

@Esakkiappan_Balaji, check the ‘&key’ try change it to ‘&key=’

It looks like a Flutter error. The error is saying you can’t access the variables: location_url, _latitude,…
And it is indicating why:

This is telling you that those variables are not available at the time of creating getlocationUrl.

If you paste the whole code I may be able to tell you where to put it. But regularly you can access variables in the same widget inside the Build method, the init or any other method inside the Widget that is executed after initstate(). Or global variables that can be accessed everywhere.

In this case I guess: lication_ulr, _latitud and _longtitude are created in the same Widget, but the Key should be saved and access securely. You can use this package for this. It uses the secure APIs of android and iOS to save the data.

2 Likes

Thank you. After making it as global variable it works.

3 Likes