【发布时间】:2020-11-20 12:35:17
【问题描述】:
我已经尝试解决这个错误好几个小时了,但似乎无法修复它。我的应用从快速加载屏幕转到主屏幕,但在此期间,屏幕呈红色闪烁一秒钟,并出现以下错误:
在构建 HomeScreen(dirty, state: _HomeScreenState#9b318) 时引发了以下 RangeError: RangeError(索引):无效值:有效值范围为空:0
我已经设法将它隔离在我的代码中,它是我显示预测信息的底部容器。
Container(
height: 150,
margin: EdgeInsets.fromLTRB(30, 0, 0, 30),
decoration: BoxDecoration(
color: Color(0xFF2F3148),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
bottomLeft: Radius.circular(30.0),
),
),
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: selectedWeather(),
),
],
),
),
],
),
SelectedWeather 方法是这样的:
///Returns the hourly or daily weather forecast based on which tab is selected.
///selectedIndex is 0 by default, when "This Week" is selected, it becomes 1, returning
///the daily weather forecast. Used as a child of the final Row in build().
List<Widget> selectedWeather() {
if (selectedIndex == 0) {
return [
hourlyWeather[0],
hourlyWeather[1],
hourlyWeather[2],
hourlyWeather[3],
hourlyWeather[4],
hourlyWeather[5],
hourlyWeather[6],
hourlyWeather[7],
hourlyWeather[8],
hourlyWeather[9],
hourlyWeather[10],
hourlyWeather[11],
];
} else if (selectedIndex == 1) {
return [
dailyWeather[0],
dailyWeather[1],
dailyWeather[2],
dailyWeather[3],
dailyWeather[4],
dailyWeather[5],
dailyWeather[6],
];
} else {
return [OvalWeather("null", 0, "null")];
}
}
这段代码所做的只是根据用户点击的内容返回相应的预测信息。我怀疑这是导致问题的原因,就像在我的堆栈跟踪中一样:
The relevant error-causing widget was:
HomeScreen file:///E:/Projects/flutter/myapps/clear_skies/lib/screens/LoadingScreen.dart:37:18
When the exception was thrown, this was the stack:
#0 List.[] (dart:core-patch/growable_array.dart:146:60)
#1 _HomeScreenState.**selectedWeather** (package:clear_skies/screens/HomeScreen.dart:356:22)
#2 _HomeScreenState.build (package:clear_skies/screens/HomeScreen.dart:521:41)
#3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
我觉得主要问题是加载 UI 时没有先获取信息。当然,我不能使 build() 小部件异步,但我已经使方法 updateUI() 异步,它填充 selectedWeather() 中使用的列表。我不能使 selectedWeather() 异步,因为 listView 中 Row 的 Children 部分需要一个列表而不是 Future。该应用程序加载并完美运行,仅在创建屏幕后一秒钟左右,但我无法部署该应用程序并弹出此红色屏幕。
我尝试在 initState() 中填充天气预报列表,但这会使我的应用程序崩溃。此外,当我只是注释掉那部分代码时,会出现另一个错误,我认为这是由相同原因引起的,在没有先等待信息的情况下填充内容。
必须为 Text 小部件提供非空字符串。 'package:flutter/src/widgets/text.dart':断言失败:第 298 行 pos 10:'data != null'
然而,这个错误也会在屏幕加载后瞬间消失。
我该怎么办?
【问题讨论】:
-
尝试使用
FutureBuilder(api.flutter.dev/flutter/widgets/FutureBuilder-class.html)。 -
您是否尝试过在容器中更改行中的交叉轴对齐方式。
标签: android flutter debugging dart error-handling