0

I am trying to get the weather of a location as a result of api call to the OpenWeatherApi. The async function getLocationAndWeatherData() is used to get the data. Now after getting the data, I need to send this data to a new screen. So I've used the arguments parameter. Now, when I use the Navigator.pushNamed() after getting the weather data, I'm getting the warning as mentioned in the question. So what's the workaround?

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import '../services/location.dart';
import '../services/networking.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    super.initState();
  }

  bool pressed = false;

  Widget loadingAndNext() {
    setState(() {
      pressed = false;
    });
    return Center(
      child: SpinKitDoubleBounce(
        color: Colors.white,
        size: 50.0,
      ),
    );
  }

  Widget mainScreen() {
    return Center(
      child: TextButton(
        onPressed: () {
          setState(() {
            pressed = true;
            getLocationAndWeatherData();
          });
        },
        child: Container(
          padding: EdgeInsets.all(18.0),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.white,
          ),
          child: Text("Get Location"),
        ),
      ),
    );
  }

  Future<dynamic> getLocationAndWeatherData() async {
    Location location = Location();
    await location.getCurrentLocation();
    double lat = location.getLatitude();
    double lon = location.getLongitude();
    NetworkHelper networkHelper = NetworkHelper(lat: lat, lon: lon);
    var x = await networkHelper.getData();
    Navigator.pushNamed(context, "/location", arguments: {'weatherData': x});
    pressed = false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: !pressed ? mainScreen() : loadingAndNext());
  }
}

After awaiting for the result in getLocationAndWeatherData(),when I use the Navigator.pushNamed(),I get a warning that I shouldn't use BuildContexts here. If I use this method in setState, I need it to be asynchronous. Can I use async and await in setState? If not, how do I get rid of this warning?

Bhargav S
  • 61
  • 1
  • 6

1 Answers1

0

try if (!mounted) return ; right before Navigation

sachin
  • 13
  • 4