![](/img/trans.png)
[英]Flutter 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
我無法使用 flutter 和 firebase 從列表視圖中的項目中的另一個屏幕檢索數據。即使使用添加調用條件,我仍然遇到此錯誤?
或者當我添加 null 時檢查!
.
我正在嘗試從另一個屏幕的列表視圖中添加對某個項目的評論,為此我嘗試檢索該項目的標題。 然后,當用戶添加評論時,評論將添加到 firestore 中,並添加到包含項目標題和評論的文檔中。
問題是我在這一行中得到了那個錯誤:
then((value) => value.data()["titre"])
我嘗試添加!
或者?
,但它只是不起作用,問題不斷發生。 有人說我應該將我轉換為then((value) =\> value.data\["titre"\])
,但不知道有人能幫我解決嗎?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
class add_comment extends StatefulWidget {
final DocumentReference docRef;
const add_comment({key, required this.docRef, required titre})
: super(key: key);
@override
State<add_comment> createState() => _add_commentState();
}
class _add_commentState extends State<add_comment> {
TextEditingController commentController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: EdgeInsets.all(5),
child: Row(
children: [
Expanded(
child: TextFormField(
controller: commentController,
minLines: 1,
maxLength: 5,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15))),
)),
SizedBox(
width: 5,
),
CircleAvatar(
radius: 25,
backgroundColor: Colors.green,
child: IconButton(
icon: Icon(Icons.send, color: Colors.white),
onPressed: () async {
final Map<String, dynamic> commentData = {
'title': widget.docRef
.get()
.then((value) => value.data()["titre"]),
'text': commentController.text,
};
await FirebaseFirestore.instance
.collection('comments')
.doc(widget.docRef.id)
.collection('comments')
.add(commentData);
// Clear the comment text field
commentController.clear();
// Show a message to the user
// Scaffold.of(context).showSnackBar(
// SnackBar(content: Text('Comment added')
// ),
//);
},
),
)
],
),
)
],
),
);
}
}
錯誤很明顯:因為您的value
是DocumentSnapshot
,所以它的value.data()
屬性是Object?
. 的?
這里意味着data()
可以返回 null,您的代碼需要處理它。
當value.data()
為 null 時告訴您的代碼該做什么的一個好方法是使用?
合並和??
運營商:
value.data()?["titre"] ?? "no data found"
所以在這里我們說,如果value.data()
是 null,我們將返回“找不到數據”。
但是,您的代碼中存在更多問題。 由於您正在調用widget.docRef.get()
,因此該數據是從數據庫加載的,並且是返回Future
的異步操作。 您正在使用then
處理 Future ,但是您的.then((value) =>...)
代碼永遠不會呈現該值。
我建議首先通過打印數據庫中的值來檢查代碼是否實際工作:
.then((value) => {
print(value.data()?["titre"] ?? "no data found");
})
或者因為它現在是一個代碼塊,我們可以使用比?
和??
並得到相同的結果:
.then((doc) => {
if (doc != null) {
var value = doc!
print(value["titre"]);
} else {
print("no data found");
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.