【问题标题】:Text widget crashes before it gets data from async function in Flutter/Dart文本小部件在从 Flutter/Dart 中的异步函数获取数据之前崩溃
【发布时间】:2020-08-01 05:22:30
【问题描述】:

所以我参加了 London App Brewery 的这门课程。我正在制作天气应用程序,当功能需要使用相关天气数据更新我的 UI 时出现问题。我已经完成了课程中的导师之类的所有工作,但自从他们制作了那个应用程序后,似乎发生了一些变化。

函数如下所示:

 WeatherModel weather = WeatherModel();
 int temperature;
 String weatherIcon;
 String weatherText;
 String cityName;

 @override
 void initState() {
     super.initState();
     updateUI(widget.locationWeather);
 }

 void updateUI(dynamic weatherData) {
     setState(() {
     double temp = weatherData["main"]["temp"] - 273.15;
     temperature = temp.toInt();
     int condition = weatherData["weather"][0]["id"];
     weatherIcon = weather.getWeatherIcon(condition);
     cityName = weatherData["name"];
     weatherText = weather.getMessage(temperature);
   });

这正是课程中应该可以使用的代码,但它不适合我。出现错误,说它期待未来(updateUI 函数)。所以我做了一些研究并更新了这样的功能:

void updateUI(Future<dynamic> locationWeather) async{
     var weatherData = await locationWeather;
     setState(() {
     double temp = weatherData["main"]["temp"] - 273.15;
     temperature = temp.toInt();
     int condition = weatherData["weather"][0]["id"];
     weatherIcon = weather.getWeatherIcon(condition);
     cityName = weatherData["name"];
     weatherText = weather.getMessage(temperature);
   });

所以像这样我让它有点工作。显示此数据的主屏幕有效。但是在那之前的一个屏幕,它发生了实际的 API 调用,它使用导航器切换到主屏幕。它还显示加载微调器,同时获取数据。所以情况是,我的加载屏幕显示有关文本小部件为空的错误,它切换到主屏幕,一切正常。我猜是因为这些文本小部件中的值实际上是 null,因为这个函数是在主屏幕 initState 而不是在加载屏幕上调用的。

编辑:

locationWeather 来自 Loading Screen 类:

class _LoadingScreenState extends State<LoadingScreen> {
double latitude;
double longitude;

@override
void initState() {
    super.initState();
    getLocationData();
}

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

   NetworkHelper networkHelper = NetworkHelper(
      "https://api.openweathermap.org/data/2.5/weather? 
   lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey");
   var weatherData = networkHelper.getData();

   Navigator.push(context, MaterialPageRoute(builder: (context) {
    return LocationScreen(weatherData);  // this is locationWeather
  }));
 }

【问题讨论】:

  • 你试过“Future updateUI(locationWeather) async{”吗?
  • 你是如何声明的,设置locationWeather 以及它包含什么值?
  • @Adnankarim 没有区别。加载屏幕上发生错误,应用程序进入主屏幕。 I/flutter (29276):必须向 Text 小部件提供非空字符串。 I/flutter (29276): 'package:flutter/src/widgets/text.dart': I/flutter (29276): 断言失败: line 285 pos 10: 'data != null'
  • @MidhunMP 我编辑了我的帖子。它现在显示 LoadingScreen 类以及传递给 LocationScreen(主屏幕)的内容。它基本上使用另一个名为 NetworkHelper 的类从 API 获取数据并将其传递给 LocationScreen。
  • @Polyamorous 请检查答案

标签: flutter dart


【解决方案1】:

问题是您传递的是 Future 而不是实际数据。 getData 方法返回一个未来,您需要等待结果。

var weatherData = await networkHelper.getData();

【讨论】:

  • 太棒了!这样可行。我只是错过了等待,updateUI 函数也不需要是异步的。谢谢。
猜你喜欢
  • 2020-11-04
  • 2021-08-17
  • 2018-09-08
  • 2021-08-27
  • 2021-03-24
  • 1970-01-01
  • 2020-09-04
  • 2019-04-25
  • 1970-01-01
相关资源
最近更新 更多