FutureBuilder in DART : "The method 'data' can't be unconditionally invoked because the receiver can be 'null'. Try making the call…"

huangapple go评论165阅读模式
英文:

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&#39;s been a few days now that I&#39;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 &#39;data&#39; can&#39;t be unconditionally invoked because the receiver can be &#39;null&#39;.
Try making the call conditional (using &#39;?.&#39;) or adding a null check to the target (&#39;!&#39;).`

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&#39;ve tried many things: 

`Map&lt;String, dynamic&gt; data = snapshot.data!.data();`

`    return FutureBuilder(
        future: users.doc(documentId).get(),
        builder:
            (BuildContext context, AsyncSnapshot&lt;DocumentSnapshot&gt; snapshot) {
            Map&lt;String, dynamic&gt; data = snapshot.data!.data() as Map&lt;String, dynamic&gt;;
          return ListTile(
            title: Text(data[fieldName]),
            subtitle: Text(data[fieldTitle]),
          );
        });`

Here I don&#39;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&#39;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(&#39;Users&#39;);
    return FutureBuilder(
        future: users.doc(documentId).get(),
        builder:
            (BuildContext context, AsyncSnapshot&lt;DocumentSnapshot&gt; snapshot) {
           /// success fetch data
          if(snapshot.hasData){
           Map&lt;String, dynamic&gt; data = jsonDecode(snapshot.data);
           return ListTile(
            title: Text(data[fieldName]),
            subtitle: Text(data[fieldTitle]),
          );
          }
         /// failed and throw error
          else if(snapshot.hasError){
            return Text(&#39;${snapshot.error}&#39;);
          } 
        /// 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&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt;(
        future: FirebaseFirestore.instance
            .collection(&#39;users&#39;)
            .doc(documentId) 
            .get(),
        builder: (_, snapshot) {
          if (snapshot.hasError) return Text(&#39;Error = ${snapshot.error}&#39;);
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text(&quot;Loading&quot;);
          }
          Map&lt;String, dynamic&gt; data = snapshot.data!.data()!;
          return Text(data[&#39;fieldName&#39;]); // give your valid data here
        },
      )),
    );
  }

huangapple
  • 本文由 发表于 2023年3月12日 16:23:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定