我最近迁移了我的应用程序以支持空安全。我使用provider包来管理我的应用程序状态。即使我检查了可空性,我仍然会在代码中遇到错误。下面是错误堆栈:
flutter:对空值使用了空检查运算符[VERBOSE-2:dart_vm_initializer.cc(41)] RangeError(index):无效值:有效值范围为空:0 #0 List.[](dart:core-patch/growable_array.dart:264:36)#1 Tutorials.setTutorials tutorials.dart:48 #2 _TutorialPageState.build. tutorial_page.dart:54 #3 Consumer.buildWithChild consumer.dart:179 #4 SingleChildStatelessWidget.build nested.dart:259 #5 StatelessElement.build framework.dart:5156 #6 SingleChildStatelessElement.build nested.dart:279 #7 ComponentElement.performRebuild framework.dart:5086 #8 Element.rebuild framework.dart:4805 #9 ComponentElement._firstBuild framework.dart:5068
下面是我的代码:
tutorials.dart
List<Tutorial>? _items = [];
List<Tutorial>? get items {
return [...?_items];
}
List<Tutorial>? get tutsOfASection {
return [...?_tutsOfASection];
}
Tutorial? findById(int id) {
return _tutsOfASection?.firstWhere((tut) => tut.id == id);
}
setTutorials(int sectionId) async {
final List<Tutorial>? loadedTuts = [];
var i = 0;
debugPrint("items: ${_items?[i].pid}");
if (_items?[i] == null) {
return;
} else {
do {
if (_items![i].pid == sectionId) {
loadedTuts?.add(_items![i]);
}
i++;
} while (_items!.length > i);
_tutsOfASection = loadedTuts;
}
}
字符串
tutorial_page.dart
body: Consumer<Tutorials>(builder: (context, value, child) {
if (_section?["sectionId"] != null) {
value.setTutorials(_section!["sectionId"]);
return TutorialScreen();
} else
return Container();
}),
型
1条答案
按热度按时间niknxzdl1#
我认为实际上是印刷品给出了错误
字符串
当
_items
为空时,它将抛出异常。如果你把这个去掉,它可能会起作用,或者把它重写成类似这样的东西型
编辑:
实际上这张支票也有同样的问题
型
如果_items为空,则会崩溃,因此将其更改为例如
型