Here is my flutter code where I try to use FutureBuilder
but encounter problems due to the null protection in 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();
}
}
});
}
}
The part that creates the problem is the following:
if (snapshot.data.entitlements.active.isNotEmpty)
And the error message:
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 ('!').
I tried updating it as the following:
else if (snapshot.data!.entitlements.active.isNotEmpty)
... but it did not help.
Any ideas on how I am supposed to deal with it?
Note: I did not paste the entire code as it involves a lot of opther logic that is not relevant to this question. I hope the pseudo code above will still help.