[英]Flutter: RangeError (index): Invalid value: Valid value range is empty: 0
List<String> results = [];
class History extends StatefulWidget {
final bool isDarkMode;
final List<String> results;
final List<String> types;
History({this.isDarkMode, this.results, this.types});
_HistoryState createState() => _HistoryState(isDarkMode, results, types);
}
class _HistoryState extends State<History> {
_HistoryState(this.isDarkMode, this.results, this.types);
final bool isDarkMode;
final List<String> results;
final List<String> types;
@override
Widget build(BuildContext context) {
Color bgColor = this.isDarkMode ? Color(0xd91D201F) : Colors.white70;
Color appBarColor = this.isDarkMode ? Color(0xff1C1D21) : Color(0xd6E8E9F3);
Color iconColor = this.isDarkMode ? Colors.black87 : Color(0xe7A6A6A8);
Color textColor = this.isDarkMode ? Colors.grey[600] : Colors.black;
List reversed = results.reversed.toList();
return Scaffold(
backgroundColor: bgColor,
body: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: results.length,
itemBuilder: (context, index) =>
Card(
color: isDarkMode ? Colors.white10 : Colors.white,
child: ListTile(
leading: Text(reversed[index], style: TextStyle(
color: textColor,
fontWeight: FontWeight.bold,
fontSize: 50),),
trailing: Text(types[index]),
),
),
),
),
],
)
);
}
}
當我傳遞一個只有一個項目的列表時,它會向我顯示標題上的錯誤,但是如果我在列表中添加更多項目,它會顯示它們,但總是沒有第一個項目並且出現紅色錯誤。 許多其他人收到此錯誤,但我找不到適合我的解決方案。 任何幫助,將不勝感激。
錯誤日志:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following RangeError was thrown building:
RangeError (index): Invalid value: Valid value range is empty: 0
When the exception was thrown, this was the stack:
#0 List.[] (dart:core-patch/growable_array.dart:146:60)
#1 _HistoryState.build.<anonymous closure> (package:dices_app/history.dart:47:45)
#2 SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:446:22)
#3 SliverMultiBoxAdaptorElement._build.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1134:67)
#4 _HashMap.putIfAbsent (dart:collection-patch/collection_patch.dart:139:29)
當您嘗試訪問的 List 索引為空或不存在時,會出現錯誤“RangeError (index): Invalid value: Valid value range is empty: 0”。 由於 class 中有兩個 List 被訪問( results
和types
),因此請確保兩者具有相同的長度以避免訪問超出范圍的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.