首页 文章

颤动'Strict'模式?

提问于
浏览
3

在大多数语言中,当您尝试使用空指针时,将抛出异常 . 然而,在Flutter中,情况似乎并非如此 . 它只是停止执行该功能,而不是抛出异常 .

void test() {
   Map<String, dynamic> testObject = null;

   // attempt to call a function on a null pointer
   var contains = testObject.containsKey("test");

   //will never execute:
   print("never prints");
}

这在 生产环境 应用程序中很好 . 但是当我开发一个应用程序时,我想知道我的应用程序何时尝试访问空指针 .

是否有可能在开发过程中在Flutter中启用某种“严格”模式,以便在开发过程中捕捉到这些情况?

1 回答

  • 0

    实际上,抛出了空指针异常 are .
    在日志输出中,您需要确保正确设置日志级别,即至少在"error"级别 .

    您还可以使用 trycatch 捕获异常,如下所示:

    try {
      Map<String, dynamic> testObject = null;
    
      testObject.containsKey('test');
    } catch (e) {
      // You can process the exception ("e" in this case) in this catch block.
      // print(e);
      // debugPrint(e);
    }
    

    如果捕获抛出的异常,它将不会自动打印到日志中,这意味着在捕获异常时您必须自己处理 .

相关问题