Flutter Dart "unconditionally accessed because the receiver can be 'null'." 问题

Flutter Dart "unconditionally accessed because the receiver can be 'null'." problem

这是我的 flutter 代码,我尝试使用 FutureBuilder 但由于 Dart 中的空保护而遇到问题。

class AbcClass extends StatefulWidget {
  @override
  _AbcClassState createState() =>
      _AbcClassState();
}

class _AbcClassState
    extends State<AbcClass>
    with AutomaticKeepAliveClientMixin {
  _AbcClassState();

  Future? _purchaserInfoSnapshot;

  @override
  void initState() {
    _purchaserInfoSnapshot = setPurchaserInfo();
    super.initState();
  }

  setPurchaserInfo() async {
    PurchaserInfo purchaserInfo = await getPurchaserInfo();

    Purchases.addPurchaserInfoUpdateListener((purchaserInfo) async {
      if (this.mounted) {
        setState(() {
          _purchaserInfoSnapshot = Future.value(purchaserInfo);
        });
      }
    });

    return purchaserInfo;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    
    return FutureBuilder(
        future: _purchaserInfoSnapshot,
        builder: (context, snapshot) {
          if (!snapshot.hasData ||
              snapshot.data == null ||
              snapshot.connectionState != ConnectionState.done) {
            return Center(
                child: Text(
              'Connecting...',
              style: Theme.of(context).textTheme.headline3,
            ));
          } else {
            if (snapshot.data.entitlements.active.isNotEmpty) {
            
              return Scaffold(...);
            } else {
              return MakePurchase();
            }
          }
        });
  }
}

产生问题的部分如下:

if (snapshot.data.entitlements.active.isNotEmpty)

错误信息:

The property 'entitlements' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').

我试过如下更新它:

else if (snapshot.data!.entitlements.active.isNotEmpty)

...但没有帮助。

关于我应该如何处理它有什么想法吗?

注意:我没有粘贴整个代码,因为它涉及很多与该问题无关的其他逻辑。我希望上面的伪代码仍然有用。

您可能已经在项目中启用了 null-safety。现在编译器不会让你编译不确定不会抛出 Null Exception 错误的代码(比如尝试访问 nullable[=33= 的 属性 ] 变量而不检查它是否首先 null)

你可以用 bang ! 运算符标记它并告诉编译器这个变量永远不会为空,这可能不是真的,所以在使用它时要小心。

或者您可以在访问其属性或尝试对其调用方法之前检查该变量是否 null

试试这个:

final active = snapshot.data?.entitlements?.active;
if (active != null && active.isNotEmpty)

我还看到您尝试先检查 snapshot.data 是否不是 null。但请记住,要使 flow-analysis 起作用,您必须将要测试的变量分配给本地最终变量。

喜欢:

final data = snapshot.data;
if (!snapshot.hasData || data == null || snapshot.connectionState != ConnectionState.done) {
  return ...