1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Is Checking mounted Necessary for Quick Async Operations in Flutter?

Discussão em 'Mobile' iniciado por Stack, Novembro 3, 2024 às 07:03.

  1. Stack

    Stack Membro Participativo

    I have an asynchronous function _getLocation, with multiple async method calls. Based on their results, I perform some actions using SetState. I understand that it is not a mandatory to check for mounted, but I've heard it can prevent errors if the user navigates to another page while an async operation is still in progress. Do it really can happens(This issue hasn’t affected me in my experience with Flutter so far) and do I need to check mounted every time for async operations? Isn't it excessive? If it is, in which cases would it be beneficial to use it?

    Future<void> _getLocation() async {
    try {
    Position position = await _determinePosition();
    if (!mounted) return;
    setState(() {
    coordinates = "${position.latitude} ${position.longitude}";
    });

    List<Placemark> placemarks =
    await placemarkFromCoordinates(position.latitude, position.longitude);

    if (!mounted) return;

    if (placemarks.isNotEmpty) {
    String city = placemarks[0].locality ?? 'City not found';
    setState(() {
    locationCity = city;
    });
    try {
    WeatherFactory wf =
    WeatherFactory("...");
    Weather weather = await wf.currentWeatherByCityName(city);

    if (!mounted) return;
    print("weather: ${weather}");
    } catch (weatherError) {
    if (!mounted) return;
    print("Weather fetch error: $weatherError");
    }
    }
    } catch (e) {
    if (!mounted) return;
    setState(() {
    coordinates = "";
    locationCity = "";
    });
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
    content: Text(
    'Geolocation is not available, please enable it in your App settings')));
    }
    }


    method "_determinePosition" - classic one, that can return value with timeout

    return await Geolocator.getCurrentPosition(
    locationSettings: locationSettings,
    ).timeout(const Duration(seconds: 5));

    Continue reading...

Compartilhe esta Página