這是我嘗試使用的顫振代碼,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)
......但它沒有幫助。
關于我應該如何處理它的任何想法?
注意:我沒有粘貼整個代碼,因為它涉及許多與此問題無關的 opther 邏輯。我希望上面的偽代碼仍然會有所幫助。
uj5u.com熱心網友回復:
您可能在專案中啟用了空安全。現在編譯器不會讓你編譯它不確定不會拋出Null Exception錯誤的代碼(比如嘗試訪問可空變數的屬性而不檢查它是否不是null第一個)
您可以使用 bang!運算子標記它并告訴編譯器此變數永遠不會為空,這可能不是真的,所以在使用它時要注意。
或者,您可以null在訪問其屬性或嘗試對其呼叫方法之前檢查該變數是否不存在。
嘗試這個:
final active = snapshot.data?.entitlements?.active;
if (active != null && active.isNotEmpty)
我也看到你試圖檢查是否snapshot.data不是null第一次。但是請記住,要使流分析起作用,您必須將您嘗試測驗的變數分配給區域最終變數。
喜歡:
final data = snapshot.data;
if (!snapshot.hasData || data == null || snapshot.connectionState != ConnectionState.done) {
return ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/339521.html
上一篇:RangeError(索引):無效值:有效值范圍為空:嘗試檢查字串時為0
下一篇:FlutterDart-'Map<dynamic,dynamic>'不能分配給引數型別'Map<int,Color>'
