firebase - TypeError:无法读取 null 的属性“Symbol(dartx._get)”(在 Flutter 中添加 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();
}
编辑:我的构建方法如下:我正在使用网络视图插件来显示支付页面。我的目的是读取 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
});
你注意到paid 没有setState
在它里面初始化,所以你的 if 语句没有对paid
. 将其更改为:
.listen((DocumentSnapshot documentSnapshot) {
Map<String, dynamic> firestoreInfo = documentSnapshot.data();
setState(() {
paid = firestoreInfo['status'];
});
if(firestoreInfo['status']) Navigator.pop(context);
});
如果您有任何问题或这没有解决您的问题,请在下方评论
推荐阅读
- python - 当它与碰撞时,如何使矩形重新出现在屏幕的不同部分
- javascript - 为什么列表没有出现在页面上?我的 React-Redux (Api) 应用程序中有哪些错误?以及如何修复它们?
- c++ - 从文件中的一行读取特定数据 - C++
- sql - 从 Oracle 查询生成 XML 文件
- oracle - 跟踪文件 oracle。如何将名称“SYS_TEMP_0FD9D6616_3CFB8B”(或对象 ID = -40016362)与特定的物化块匹配(使用 as)
- python - 保留以前的单元格值并复制到下一个单元格 python pandas dataframe
- python - 对具有多个值的python列表进行阈值处理
- html - 我可以在不手动指定每个可能的嵌套级别的情况下更改纯 HTML/CSS 中任意嵌套的详细信息标签的属性吗?
- linux - awk 递增变量计数 12,615,766 两次
- java - 在不改变另一个人的类的情况下,我如何要求它使用我的 Scanner 版本(作为内部类埋藏)而不是 java.util.Scanner?