![](/img/trans.png)
[英]The method [] can't be unconditionally invoked because the receiver can be null
[英]The method '[]' can't be unconditionally invoked because the receiver can be 'null'
我是 Flutter 的新手。我正在尝试开发一个应用程序。
我想显示 Firebase 数据库中的员工列表。 但是,我收到以下错误。
错误:
无法无条件调用方法“[]”,因为接收者可以为“null”。 尝试使调用有条件(使用'?.')或向目标('.')添加 null 检查。
科德拉里姆:
`import 'package:calendar/page/mainPage.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Staff extends StatefulWidget {
@override
_StaffState createState() => _StaffState();
}
class _StaffState extends State<Staff> {
final _firestore = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
// ignore: unused_local_variable
CollectionReference staffRef = _firestore.collection('staff');
return Scaffold(
appBar: AppBar(
title: Text("Personel Listesi"),
backgroundColor: Colors.redAccent[400],
actions: <Widget>[
IconButton(
icon: Icon(Icons.home),
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (_) => MainPage()),
(route) => true);
},
),
],
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Column(
children: [
StreamBuilder<QuerySnapshot>(
stream: staffRef.snapshots(),
builder: (BuildContext context, AsyncSnapshot asyncSnapshot) {
if (asyncSnapshot.hasError) {
return Center(
child: Text(
"Bir hata oluştu, lütfen tekrar deneyiniz."));
} else {
if (asyncSnapshot.hasData) {
List<DocumentSnapshot> listStaff =
asyncSnapshot.data.docs;
return Flexible(
child: ListView.builder(
itemBuilder: (context, index) {
return Card(
elevation: 20,
color: Colors.greenAccent[200],
child: ListTile(
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () async {
await listStaff[index]
.reference
.delete();
},
),
title: Text(
'${listStaff[index].data['nameSurname']}',
style: TextStyle(fontSize: 20),
),
subtitle: Column(
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Text(
'${listStaff[index].data['tip']}',
style: TextStyle(fontSize: 14),
),
],
),
Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Text(
'${listStaff[index].data['mail']}',
style: TextStyle(fontSize: 14),
),
],
),
Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Text(
'${listStaff[index].data['phone']}',
style: TextStyle(fontSize: 14),
),
],
),
],
),
),
);
},
itemCount: listStaff.length),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}
},
),
],
),
),
),
),
);
}
}
`
我和提问者有同样的问题,解决方案来自这篇文章。 我把它留在这里,以防其他人有这个问题。 https://fileidea.com/2021/05/05/method-cant-be-unconditionally-invoked-because-the-receiver-can-be-null-with-firestore/
前:
final mySnapStream = messagesCollection
.orderBy('date', descending: true)
.limit(100)
.snapshots()
.map((obj) => obj.docs
.map((e) => new MyItem(
e.data()['myFieldOne'],
e.data()['myFieldThree'],
e.data()['myFieldFour']))
.toList());
after:
final mySnapStream = messagesCollection
.orderBy('date', descending: true)
.limit(100)
.snapshots()
.map((obj) => obj.docs
.map((e) => new MyItem(
(e.data() as dynamic)['myFieldOne'],
(e.data() as dynamic)['myFieldThree'],
(e.data() as dynamic)['myFieldFour']))
.toList());
在新的 flutter 更新中,我们不需要添加.data()
我的代码如下
title: Text(
**'${listStaff[index].data['nameSurname']}',**
style: TextStyle(fontSize: 20),
),
像这样更改它修复了错误。
title: Text(
**'${listPersonel[index]['nameSurname']}'**,
style: TextStyle(fontSize: 20),
),
这是一个典型的空安全相关错误。 我没有尝试代码,我猜可能将asyncSnapshot.data.docs
分配给listStaff
可能会返回null ,但是您声明的类型List<DocumentSnapshot>
不允许这样做。 如果您 100% 确定此分配不会返回 null 值,则可以添加“,”以确保编译器将是 List。 所以它会让你使用方法,虽然如果你希望这个列表是空的? 你可以简单地添加','来显示它? 而不是使用'..'来使用方法:它就像。 检查 object 是否为 null 并仅在不是时才在此方法上执行方法。
如果您正在访问可为空的List
或Map
上的元素,则会收到此错误。 让我们了解它的List
,您可以为您的Map
应用相同的解决方案。
例如:
List<int>? someList;
void main() {
int a = someList[0]; // Error
}
使用局部变量:
var list = someList; if (list;= null) { int a = list[0]; // No error }
使用?
和??
:
int a = someList?[0]?? -1; // -1 is the default value if List was null
使用!
仅当您确定List
不是null
时才使用 bang 运算符。
int a = someList;[0];
FutureBuilder
/ StreamBuilder
的人:您可以通过两种方式解决错误:
为您的FutureBuilder
/ StreamBuilder
指定一个类型
FutureBuilder<List<int>>( // <-- type 'List<int>' is specified. future: _listOfInt(), builder: (_, snapshot) { if (snapshot.hasData) { List<int> myList = snapshot.data;; // <-- Your data } return Container(), }, )
使用as
将Object
向下转换为您的类型,例如List
或Map
。
FutureBuilder( future: _listOfInt(), builder: (_, snapshot) { if (snapshot.hasData) { var myList = snapshot.data; as List<int>; // <-- Your data using 'as' } return Container(), }, )
如果你使用 FutureBuilder 试试 FutureBuilder
对于 Firebase snapshot.data!['YourData']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.