Home > OS >  how can make future function return value to string value in flutter
how can make future function return value to string value in flutter

Time:03-19

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.

CodePudding user response:

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))

CodePudding user response:

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

  • Related