0

I have make a file getLocation.dart contain function return a city name the final code is that:

// ignore_for_file: avoid_print

import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';

Future<Position> getGeoLocationPosition() async {
  bool serviceEnabled;
  LocationPermission permission;
  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the
    // App to enable the location services.
    await Geolocator.openLocationSettings();
    return Future.error('Location services are disabled.');
  }
  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.
      return Future.error('Location permissions are denied');
    }
  }
  if (permission == LocationPermission.deniedForever) {
    // Permissions are denied forever, handle appropriately.
    return Future.error(
        'Location permissions are permanently denied, we cannot request permissions.');
  }
  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  return await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high);
}

getName() async {
  var pos = await getGeoLocationPosition();
  List<Placemark> placemarks =
      await placemarkFromCoordinates(pos.latitude, pos.longitude);
  var place = placemarks[0];
  return place.locality;
}

My problem is when I use my weather API it required me city name that get from my getLocation.dart but I can't use it because its future function.

I want to convert the value to a string and store it in variable.

Filburt
  • 17,626
  • 12
  • 64
  • 115
L Amer
  • 21
  • 7

2 Answers2

0

You may try using:

[1]async/await(https://dart.dev/codelabs/async-await): example:

final cityName = await your_future_function();
print(cityName) // it is a String value for you

[2] using then(https://api.flutter.dev/flutter/dart-async/Future-class.html),example:

your_future_function.then((cityName) => handleValue(cityName))
nielsezeka
  • 206
  • 2
  • 2
0

Change getName() async { to Future<String> getName() async { and then when you call getName, await it: String name = await getName()

Andrew
  • 155
  • 1
  • 9
  • 1
    it tell me A value of type 'String?' can't be returned from the function 'getName' because it has a return type of 'Future'.dartreturn_of_invalid_type – L Amer Mar 18 '22 at 17:53