[英]Flutter error: The property 'docs' can't be unconditionally accessed because the receiver can be 'null'
I am struggling to resolve these two errors.我正在努力解决这两个错误。
error: The property 'docs' can't be unconditionally accessed because the receiver can be 'null'.错误:无法无条件访问属性“docs”,因为接收者可以为“null”。 (unchecked_use_of_nullable_value at [church_app] lib\Screens\DevotionalList.dart:23) (unchecked_use_of_nullable_value 在 [church_app] lib\Screens\DevotionalList.dart:23)
error: The parameter 'devotional' can't have a value of 'null' because of its type, but the implicit default value is 'null'.错误:参数“devotional”因其类型不能具有“null”值,但隐式默认值为“null”。 (missing_default_value_for_parameter at [church_app] lib\Screens\DevotionalList.dart:39) (在 [church_app] lib\Screens\DevotionalList.dart:39 缺少_default_value_for_parameter)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class DevotionalList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('devotionals').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text('Error: ${snapshot.error}'),
);
}
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
// Use the .docs property to access the list of documents.
List<DocumentSnapshot> documents = snapshot.data.docs;
return ListView.builder(
itemCount: documents.length,
itemBuilder: (context, index) {
DocumentSnapshot devotional = documents[index];
return DevotionalTile(devotional: devotional);
},
);
},
);
}
}
class DevotionalTile extends StatelessWidget {
final DocumentSnapshot devotional;
DevotionalTile({this.devotional});
@override
Widget build(BuildContext context) {
if (devotional == null) {
return Container();
}
return ExpansionTile(
title: Text(devotional['title']),
subtitle: Text('By ${devotional['author']}'),
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(devotional['body']),
),
],
);
}
}
Any assistance would be appreciated.任何援助将不胜感激。
Tried adding null exceptions but I still run into the same error.尝试添加 null 异常,但我仍然遇到同样的错误。
at the point when your call snapshot.data.docs
, it can't be null since you checked first with the hasError
, so you can tell this to Dart by explicitly adding a !
当您调用snapshot.data.docs
时,它不可能是 null,因为您首先使用hasError
进行了检查,因此您可以通过显式添加一个!
, instead of this: ,而不是这个:
List<DocumentSnapshot> documents = snapshot.data.docs;
add !
添加!
, so it will be this: ,所以它会是这样的:
List<DocumentSnapshot> documents = snapshot.data.docs!;
this will fix both the error you're facing.这将解决您面临的两个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.