dart flutter:用于空值的空检查运算符,未处理异常:RangeError(index):无效值:有效值范围为空:0

pn9klfpd  于 2023-07-31  发布在  Flutter
关注(0)|答案(1)|浏览(207)

我最近迁移了我的应用程序以支持空安全。我使用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();
  }),

niknxzdl

niknxzdl1#

我认为实际上是印刷品给出了错误

debugPrint("items: ${_items?[i].pid}");

字符串
_items为空时,它将抛出异常。如果你把这个去掉,它可能会起作用,或者把它重写成类似这样的东西

debugPrint("items: ${(_items ?? []).isEmpty ? 'null' : _items?[i].pid}");


编辑:
实际上这张支票也有同样的问题

if (_items?[i] == null) {


如果_items为空,则会崩溃,因此将其更改为例如

if (_items == null || _items.isEmpty || _items?[i] == null) {

相关问题