类型错误:无法读取 null 的属性'Symbol(dartx._get)'(在添加 Firestore 侦听器时在颤振中)



我无法将监听器添加到我的firestore文档中。我得到了上面的错误,我不知道是什么原因造成的。我的代码如下:

StreamSubscription<DocumentSnapshot> listener;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
_initListener();
});
}
_initListener() async {
listener = FirebaseFirestore.instance
.collection('Ref to my collection path')
.doc('status')
.snapshots()
.listen((DocumentSnapshot documentSnapshot) {
Map<String, dynamic> firestoreInfo = documentSnapshot.data();
setState(() {
paid = firestoreInfo['status'];
});
if(paid) Navigator.pop(context);
});
listener.onError((handleError){
if(DEBUG) print('Cannot attach listener: Error: $handleError');
});
}
@override
void dispose() {
listener.cancel();
super.dispose();
}

EDIT:我的构建方法如下:我正在使用一个网络视图插件来显示一个支付页面。我的意图是阅读firebase上的数据,看看它何时更新,然后转到付款成功或付款失败页面。

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.white, //change your color here
),
elevation: 0.0,
title: Text("PAYMENT", style: Header),
backgroundColor: Provider.of<CP>(context, listen: false).primary,
),
backgroundColor: Color(0xfff6f7f8),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(13.0),
child: Text('Please enter your payment details'),
),
Expanded(
child: Container(
padding: EdgeInsets.all(20),
child: EasyWebView(
onLoaded: (){},
src: 'PATH FOR PAYMENT URL',
isHtml: false, // Use Html syntax
isMarkdown: false, // Use markdown syntax
convertToWidgets: false, // Try to convert to flutter widgets
width: MediaQuery.of(context).size.width,
),
),
),
Padding(
padding: const EdgeInsets.all(13.0),
child: Text('Your payment info is encrypted and protected by STRIPE', style: TextStyle(fontSize: 12, fontStyle: FontStyle.italic),),
),
],
),
);
}

我认为你的问题就在这里:

.listen((DocumentSnapshot documentSnapshot) {
Map<String, dynamic> firestoreInfo = documentSnapshot.data();
setState(() {
paid = firestoreInfo['status'];
});
if(paid) Navigator.pop(context); // issue
});

您注意到payed不是在setState外部初始化的,而是在它内部初始化的,所以您的if语句对paid没有accuss。更改为:

.listen((DocumentSnapshot documentSnapshot) {
Map<String, dynamic> firestoreInfo = documentSnapshot.data();
setState(() {
paid = firestoreInfo['status'];
});
if(firestoreInfo['status']) Navigator.pop(context);
});

如果你有任何问题,或者如果这没有解决你的问题,请在下面评论

因此,问题是paid = firestoreInfo['status'];返回null。有一次我把空检查放在适当的位置,错误就消失了。payed变量被全局初始化为false。

我不是为这个特定的问题写这个答案,而是为任何在使用Firebase和Flutter时出现TypeError: Cannot read properties of null (reading 'Symbol(dartx.***)')错误的人写这个答案。我没能得到字段,也没能联系到任何文档或集合,唯一出现的就是这个错误。

除了一件小事:,一切都准备好了

Firebase控制台>Firestore数据库>规则>第5行:从allow read, write: if false;allow read, write: if true;

我试图在没有用户登录的情况下访问数据,所以唯一必须更改的是这一点。我希望这有一天能帮助到别人。

最新更新