英文:
FutureBuilder in DART : "The method 'data' can't be unconditionally invoked because the receiver can be 'null'. Try making the call..."
问题
'code'和'CastError (Null check operator used on a null value)' 不要翻译。
以下是翻译后的内容:
已经有几天了,我一直在按照教程学习如何在Flutter中使用Firebase来编写代码。然而,我完全卡在一个步骤上,而其他人却能够成功完成,我已经百分之百复制了代码,但出现了以下错误:
“方法 'data' 无法无条件调用,因为接收器可能为 'null'。
尝试使调用具有条件性(使用 '?.') 或向目标添加空检查('!')。”
以下是代码:
```dart
class GetUserData extends StatelessWidget {
final String documentId;
final String fieldName;
final String fieldTitle;
GetUserData(
{super.key,
required this.documentId,
required this.fieldName,
required this.fieldTitle});
@override
Widget build(BuildContext context) {
CollectionReference users = firestore.collection('Users');
return FutureBuilder(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
Map<String, dynamic> data = snapshot.data.data();
return ListTile(
title: Text(data[fieldName]),
subtitle: Text(data[fieldTitle]),
);
});
}
}
我尝试了很多方法:
Map<String, dynamic> data = snapshot.data!.data();
return FutureBuilder(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return ListTile(
title: Text(data[fieldName]),
subtitle: Text(data[fieldTitle]),
);
});
在这里我没有错误,但在调试时会出现崩溃“_CastError (Null check operator used on a null value)”。
我已经到处寻找解决方法,但不明白如何解决这个问题。
非常感谢你的帮助,
<details>
<summary>英文:</summary>
It's been a few days now that I'm working on a flutter code by following tutorials to learn how to use Firebase with it. Nevertheless I completely block on a step that the person manages to realize, I have however copied the code at 100% and here is the error that I have:
`The method 'data' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!').`
Here is the code:
class GetUserData extends StatelessWidget {
final String documentId;
final String fieldName;
final String fieldTitle;
GetUserData(
{super.key,
required this.documentId,
required this.fieldName,
required this.fieldTitle});
@override
Widget build(BuildContext context) {
CollectionReference users = firestore.collection('Users');
return FutureBuilder(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
Map<String, dynamic> data = snapshot.data.data();
return ListTile(
title: Text(data[fieldName]),
subtitle: Text(data[fieldTitle]),
);
});
}
}
I've tried many things:
`Map<String, dynamic> data = snapshot.data!.data();`
` return FutureBuilder(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return ListTile(
title: Text(data[fieldName]),
subtitle: Text(data[fieldTitle]),
);
});`
Here I don't have the error but a crash when I debug with `_CastError (Null check operator used on a null value)`
I have looked everywhere and I don't understand how to solve this,
Thank you so much for your help,
</details>
# 答案1
**得分**: 0
尝试处理所有情况
```dart
@override
Widget build(BuildContext context) {
CollectionReference users = firestore.collection('Users');
return FutureBuilder(
future: users.doc(documentId).get(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
/// 成功获取数据
if(snapshot.hasData){
Map<String, dynamic> data = jsonDecode(snapshot.data);
return ListTile(
title: Text(data[fieldName]),
subtitle: Text(data[fieldTitle]),
);
}
/// 失败并抛出错误
else if(snapshot.hasError){
return Text('${snapshot.error}');
}
/// 加载中情况
else {
return Center(child: CircularProgressIndicator());
}
});
}
英文:
try to handle all condition
@override
Widget build(BuildContext context) {
CollectionReference users = firestore.collection('Users');
return FutureBuilder(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
/// success fetch data
if(snapshot.hasData){
Map<String, dynamic> data = jsonDecode(snapshot.data);
return ListTile(
title: Text(data[fieldName]),
subtitle: Text(data[fieldTitle]),
);
}
/// failed and throw error
else if(snapshot.hasError){
return Text('${snapshot.error}');
}
/// loading condition
else {
return Center(child:CircularProggressIndicator());
}
});
}
答案2
得分: 0
你没有正确解码来自 Firebase 的响应,请考虑以下代码:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>(
future: FirebaseFirestore.instance
.collection('users')
.doc(documentId)
.get(),
builder: (_, snapshot) {
if (snapshot.hasError) return Text('Error = ${snapshot.error}');
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
Map<String, dynamic> data = snapshot.data!.data()!;
return Text(data['fieldName']); // give your valid data here
},
)),
);
}
英文:
You are not decoding the response from the firebase properly, try considering the below code:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
future: FirebaseFirestore.instance
.collection('users')
.doc(documentId)
.get(),
builder: (_, snapshot) {
if (snapshot.hasError) return Text('Error = ${snapshot.error}');
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
Map<String, dynamic> data = snapshot.data!.data()!;
return Text(data['fieldName']); // give your valid data here
},
)),
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论