【问题标题】:My values are being loaded only after hot reloading仅在热重新加载后才加载我的值
【发布时间】:2021-12-02 23:48:11
【问题描述】:

我一直在开发一个显示实时天气数据的天气应用程序。我对 Flutter 和 Dart 比较陌生。

当我运行代码时,应用程序会构建,而不是在屏幕上显示三个值,而是将所有三个值都显示为 null。 但是当我热重载时,值会出现。 有人吗?

import 'dart:convert';
import 'package:flutter/material.dart';
import 'Services/LocationServices.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  var Longitude;
  var Latitude;
  var CityName;
  var Temperature;
  var Description;
  var appid = '111267e28d8012bc99ae1aa67bb9d87f';

  void getLocation() async{
    Location location = Location();
    await location.getCurrentLocation();

    Latitude = location.latitude;
    Longitude = location.longitude;
    print('Latitude = ${location.latitude}');
    print('Longitude = ${location.longitude}');
    getData();

  }

  void getData() async{
    var url = Uri.parse('https://api.openweathermap.org/data/2.5/weather?lat=$Latitude&lon=$Longitude&appid=$appid&units=metric');
    http.Response response = await http.get(url);

    if (response.statusCode == 200){
      String Data = response.body;
      var city = jsonDecode(Data)['name'];
      CityName = city;
      var temp = jsonDecode(Data)['main']['temp'];
      Temperature = temp;
      var condition = jsonDecode(Data)['weather'][0]['description'];
      Description = condition;

      // print('City = $city');
      // print('Temperature = $temp');
      // print('Description = $condition');

    }else{
      print(response.statusCode);
    }
  }

  @override
  void initState() {
    super.initState();
    getLocation();

  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(child: Text('$CityName')),
            Center(child: Text('$Temperature')),
            Center(child: Text('$Description')),
            // Text('$temperature'),
            // Text('$temperature'),
            // Text('$temperature'),
          ],
        )
      ),
    );
  }
}

这是 LocationServices.dart 文件。 有人对我在这里做错了什么有任何想法吗?

import 'package:geolocator/geolocator.dart';

class Location{

  var latitude;
  var longitude;

  Future<void> getCurrentLocation() async{

    try{
      Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
      latitude = position.latitude;
      longitude = position.longitude;
    }
    catch(e){
      print(e);
    }
  }
}

【问题讨论】:

  • 因为你从不更新状态

标签: flutter dart async-await flutter-hotreload


【解决方案1】:

您需要调用setState 来触发StatefulWidget 中的状态更改

void getData() async {
  var url = Uri.parse(
      'https://api.openweathermap.org/data/2.5/weather?lat=$Latitude&lon=$Longitude&appid=$appid&units=metric');
  http.Response response = await http.get(url);

  if (response.statusCode == 200) {
    setState(() {
      String Data = response.body;
      var city = jsonDecode(Data)['name'];
      CityName = city;
      var temp = jsonDecode(Data)['main']['temp'];
      Temperature = temp;
      var condition = jsonDecode(Data)['weather'][0]['description'];
      Description = condition;
    });

    // print('City = $city');
    // print('Temperature = $temp');
    // print('Description = $condition');

  } else {
    print(response.statusCode);
  }
}

【讨论】:

  • 谢谢。我现在可以运行它了。
【解决方案2】:

了解FutureBuilder!我想这会对你有所帮助!

【讨论】:

    【解决方案3】:

    在所有方法之上调用 initState 中的方法只是一个简单的错误。

       @override
       void initState() {
       getLocation();
       getData();
       super.initState();
       }
    

    getLocation() 方法之前调用此方法。当您来到页面时,它会自动执行 getData()getLocation() 方法。所以不需要刷新页面。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2013-06-23
    • 2013-07-12
    • 2011-04-06
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多