[英]Firebase doesn't work cause of null-safety (DART/FLUTTER)
im using/learning FireBase for my database works.我正在为我的数据库工作使用/学习 FireBase。 My snapshot's coming like _jsonQuerySnapshot or _jsonDocumentSnapshot.我的快照就像 _jsonQuerySnapshot 或 _jsonDocumentSnapshot 一样。 But it had to be QuerySnapshot or DocumentSnapshot.但它必须是 QuerySnapshot 或 DocumentSnapshot。 Because of this i have to encode and decode my snapshot for use my datas.因此,我必须对我的快照进行编码和解码以使用我的数据。 If im' not using encode decode json im getting null or object errors all the time.如果我不使用编码解码 json 我总是得到 null 或 object 错误。 Here is my class extends from state这是我的 class 延伸自 state
class _MyHomePageState extends State<MyHomePage> {
final _firestore = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
CollectionReference moviesRef=_firestore.collection('movies');
DocumentReference babaRef = _firestore.collection('movies').doc('Baba');
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(
title: Text('FireStore Crud'),
),
body: Center(
child: Container(
child: Column(
children: [
StreamBuilder<QuerySnapshot>(
stream: moviesRef.snapshots(),
builder: (BuildContext context,AsyncSnapshot asyncSnapshot){
List<DocumentSnapshot>listOfDocumentSnapshot=asyncSnapshot.data.docs;
return Flexible(
child: ListView.builder(
itemCount: listOfDocumentSnapshot.length,
itemBuilder: (context,index){
Text('${listOfDocumentSnapshot[index].data()['name']}' ,style: TextStyle(fontSize: 24),);
},
),
);
},
),
],
),
),
),
);
}
}
and this is my error.这是我的错误。
First of all, check your data is it null or not and after that use []
on it.首先,检查您的数据是否为 null,然后在其上使用[]
。 Probably, listOfDocumentSnapshot[index].data()
is null.可能listOfDocumentSnapshot[index].data()
是 null。 If it is null, render another UI such as loading screen.如果是 null,则渲染另一个 UI,例如加载屏幕。 Namely, your loading screen must be showed until reach the data.也就是说,您的加载屏幕必须显示,直到到达数据。
for example:例如:
builder: (BuildContext context,AsyncSnapshot asyncSnapshot){
List<DocumentSnapshot> listOfDocumentSnapshot = asyncSnapshot.data.docs;
if(!listOfDocumentSnapshot.hasData || listOfDocumentSnapshot == null){
return LoadingScreen(); //etc.
}
return Flexible(
child: ListView.builder(
itemCount: listOfDocumentSnapshot.length,
itemBuilder: (context,index){
Text('${listOfDocumentSnapshot[index].data()['name']}' ,style: TextStyle(fontSize: 24),);
},
),
);
},
Futures (asynchronous programmes) need some time to get data and you have to make your UI wait until you get your data. Futures(异步程序)需要一些时间来获取数据,你必须让你的 UI 等到你获取数据。 eg database connections, read/write somethings to/from somewhere etc.例如数据库连接,从某处读/写某些东西等。
For more detail you can read this article .有关更多详细信息,您可以阅读这篇文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.