简体   繁体   中英

I am getting weird output but no errors in Flutter weather application

I am getting weird output but no errors.

1) location_handler.dart

import 'package:geolocator/geolocator.dart';

class Locator {
  //Locator({this.latitude, this.longitude});

  double? latitude;
  double? longitude;

  Future<void> getCurrentLocation() async {
    //'async' means that this function might take unknown amount of time
    //so we put async to put this operation to happen in the background.
    try {
      //using try catch block to prevent errors.
      Position posi = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.low);
      //set to low to save battery since you just need weather info.
      latitude = posi.latitude;
      longitude = posi.longitude;
    } on Exception catch (e) {
      print(e);
    }
  }
}

2) loading_screen.dart

import 'package:flutter/material.dart';
import 'package:clima/services/location_handler.dart';
import 'dart:convert'; //imported to convert/use JSON data into our project.
import 'package:http/http.dart' as http;

const myAPI = 'cant show but I have registerd and working key';

class LoadingScreen extends StatefulWidget {
      @override
      _LoadingScreenState createState() => _LoadingScreenState();
    }
    
    class _LoadingScreenState extends State<LoadingScreen> {
      late double latitood;
      late double longitood;
    
      void initState() {
        //this method is called the moment we run our app.
        super.initState();
        getLocation();
      }
    
      void getLocation() async {
        Locator loca = Locator();
        await loca.getCurrentLocation();
        latitood = loca.latitude!; //'!' is null-check.
        longitood = loca.longitude!;
        getData();
      }
    
      void getData() async {
        Uri uri = Uri.https(
          /*A Uniform Resource Identifier is a unique sequence of characters
          that identifies a logical or physical resource used by web technologies.*/
          'api.openweathermap.org', //Authority(string)
          '/data/2.5/weather', //Path(string)
          {'lat': latitood, 'lon': longitood, 'appid': myAPI},
          //Parameters of Query
        );
        http.Response response = await http.get(uri);
        //passing uri to get method to get Response.
        print(response.statusCode);
        if (response.statusCode == 200) {
          String data = response.body;
          var decodedData = jsonDecode(data);
          //decoding and putting data into decodedData variable of dynamic type.
    
          int weatherCondition = decodedData['weather'][0]['id'];
          //gets weather condition.
          print(weatherCondition);
    
          double temperature = decodedData['main']['temp'];
          //for temperature.
          print(temperature);
    
          String cityName = decodedData['name'];
          //city name.
          print(cityName);
        } else {
          print(response.statusCode);
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold();
      }
    }  

Output:

Performing hot restart...

Syncing files to device moto g52...

Restarted application in 1,518ms.

E/flutter ( 4024): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'double' is not a subtype of type 'Iterable'

E/flutter ( 4024): #0 _Uri._makeQuery. (dart:core/uri.dart:2356:18)

E/flutter ( 4024): #1 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:614:13)

E/flutter ( 4024): #2 _Uri._makeQuery (dart:core/uri.dart:2352:21)

E/flutter ( 4024): #3 new _Uri (dart:core/uri.dart:1643:13)

E/flutter ( 4024): #4 _Uri._makeHttpUri (dart:core/uri.dart:1782:12)

E/flutter ( 4024): #5 new _Uri.https (dart:core/uri.dart:1678:12)

E/flutter ( 4024): #6 _LoadingScreenState.getData (package:clima/screens/loading_screen.dart:37:19)

E/flutter ( 4024): #7 _LoadingScreenState.getLocation (package:clima/screens/loading_screen.dart:33:5)

E/flutter ( 4024):

E/flutter ( 4024):

Problem: I should be getting Weather condition, temperature, and City name. But I am getting all this please help.

Solved the problem. Just had to add 'late' keyword for both longitood and latitood variables of type double and do certain tweaks in the code.

Instead of:

 void getData() async {
            Uri uri = Uri.https(
              /*A Uniform Resource Identifier is a unique sequence of characters
              that identifies a logical or physical resource used by web technologies.*/
              'api.openweathermap.org', //Authority(string)
              '/data/2.5/weather', //Path(string)
              {'lat': latitood, 'lon': longitood, 'appid': myAPI},
              //Parameters of Query
            );

Adding $ and putting '' did the deed:

void getData() async {
    Uri uri = Uri.https(
      /*A Uniform Resource Identifier is a unique sequence of characters
      that identifies a logical or physical resource used by web technologies.*/
      'api.openweathermap.org', //Authority(string)
      '/data/2.5/weather', //Path(string)
      {'lat': '$latitood', 'lon': '$longitood', 'appid': myAPI},
      //Parameters of Query
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM