Как реализовать нулевую безопасность в простом коде flutter-dart с помощью объекта snapshot.data?

Я новичок в кодировании флаттера / дротика, пожалуйста, помогите мне решить следующее:

Вот мой код пытается получить данные из коллекции FireStore DinnerNames, но я получаю ошибку анализа объекта snapshot.data в строке:

itemCount: snapshot.data.documents.length

:

Эта проблема:

Выражение, значение которого может быть нулевым, должно быть проверено на null, прежде чем его можно будет разыменовать. Перед разыменованием убедитесь, что значение не равно null.

Вот пример кода, генерирующего ошибку:

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]),
            ); 
            }           
          }
          ),
    );

вот версия флаттера:

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)

person Davaa Ch    schedule 22.01.2021    source источник
comment
Я бы рекомендовал вам перейти на Flutter 2.2 вместо версии 1.25.   -  person DarkNeuron    schedule 27.05.2021


Ответы (2)


Если вы уверены, что объект не null к тому моменту, когда вы его используете, просто вставьте оператор Bang !, чтобы исключить возможность нулевого значения, примерно так:

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

вы уже проверяете:

snapshot.data == null

но похоже, что анализ показывает, что документы также могут быть нулевыми, поэтому попробуйте также включить:

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

или попробуйте изменить этот код:

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

к этому:

if (snapshot.data == null || snapshot.data.documents == null){
  return const Text("Snapshot.data is null..");
}
person Guilherme V.    schedule 22.01.2021