简体   繁体   English

如何使用 object snapshot.data 在简单的 flutter-dart 代码中实现空安全?

[英]How to implement null-safety in simple flutter-dart code with object snapshot.data?

I am new to flutter/dart coding, please help me solve the following:我是 flutter/dart 编码的新手,请帮我解决以下问题:

Here is my code trying to fetch data from the FireStore collection "DinnerNames" but I get an analysis error on the snapshot.data object at the line:这是我的代码,试图从 FireStore 集合“DinnerNames”中获取数据,但我在snapshot.data object 行中收到分析错误:

itemCount: snapshot.data.documents.length itemCount:snapshot.data.documents.length

: :

The problem:问题:

An expression whose value can be 'null' must be null-checked before it can be dereferenced.其值可以为“null”的表达式必须先进行空值检查,然后才能取消引用。 Try checking that the value isn't 'null' before dereferencing it.在取消引用之前尝试检查该值是否为“null”。

Here is the code sample generates the error:这是生成错误的代码示例:

CollectionReference dinners =
        FirebaseFirestore.instance.collection('DinnerNames');

    return Scaffold(
      appBar: AppBar(
        title: Text('My Dinner Voting App'),
      ),
      body: StreamBuilder(
          stream: dinners.snapshots(),
          builder: (context, snapshot){
            if (!snapshot.hasData) return const Text('Firestore snapshot is loading..');
            
            if (!snapshot.hasError)
              return const Text('Firestore snapshot has error..');
            
            if (snapshot.data == null){
              return const Text("Snapshot.data is null..");
            }else{
               return ListView.builder(
              itemExtent: 80.0,
              itemCount:  snapshot.data.documents.length,
              itemBuilder: (context, index) =>
                  _buildListItem(context, snapshot.data.documents[index]),
            ); 
            }           
          }
          ),
    );

here is the flutter version:这是 flutter 版本:

dave@DaveMacBook-Pro firebasetest % flutter --version
Flutter 1.25.0-8.2.pre • channel beta • https://github.com/flutter/flutter.git
Framework • revision b0a2299859 (2 weeks ago) • 2021-01-05 12:34:13 -0800
Engine • revision 92ae191c17
Tools • Dart 2.12.0 (build 2.12.0-133.2.beta)

If you're sure that the object is not null by the time you're using it, just insert a Bang !如果您确定 object 在您使用它时不是null ,只需插入 Bang ! operator to cast away nullability, something like this:运算符来抛弃可空性,如下所示:

ListView.builder(
  itemCount: snapshot.data!.docs.length, // <-- Notice '!'
)

you're already checking:您已经在检查:

snapshot.data == null

but it seems the analysis is indicating that documents can also be null, so try to include also:但似乎分析表明文件也可以是 null,所以也尝试包括:

if (snapshot.data.documents != null) { ... do what you need }

or try to change this code:或尝试更改此代码:

if (snapshot.data == null){
  return const Text("Snapshot.data is null..");
}

to this:对此:

if (snapshot.data == null || snapshot.data.documents == null){
  return const Text("Snapshot.data is null..");
}

If you explicitly tell dart/flutter that the type of the snapshot argument in the builder function will be 'AsyncSnapshot<QuerySnapshot>' you can let Flutter know that it will have certain attributes, like below.如果您明确告诉 dart/flutter 构建器 function 中快照参数的类型将是“AsyncSnapshot<QuerySnapshot>”,您可以让 Flutter 知道它将具有某些属性,如下所示。 You may still have to use the '?.'您可能仍需要使用“?”。 operator and 'documents' has now been changed to 'docs':运算符和“文档”现在已更改为“文档”:

    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot){ // <-- here
            if (!snapshot.hasData) return const Text('Firestore snapshot is 
        loading..');
                
            if (!snapshot.hasError)
              return const Text('Firestore snapshot has error..');
                
            if (snapshot.data == null){
              return const Text("Snapshot.data is null..");
            }else{
               return ListView.builder(
                   itemExtent: 80.0,
                   itemCount:  snapshot.data?.docs.length,
                   itemBuilder: (context, index) =>
                      _buildListItem(context, snapshot.data?.docs[index]),
                   ); 
           }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM