我正在使用 Flutter 和 Cloud Firestore,但我遇到了需要更新集合 -> 檔案中的嵌套欄位的問題。下面是我的 firestore 集合結構的螢屏截圖。我知道如何執行基本的更新方法FirebaseFirestore.instance.collection('collection_path').doc('data').update(...),但是,就我而言,檔案結構有點復雜,因此在執行更新方法的情況下我需要一些幫助。

在這里,我需要將(按按鈕)欄位status更改為true/false下strategies陣列。我可以訪問strategyName欄位,以便我可以在strategies陣列中獲取該專案并更改它...
我試過的:
ElevatedButton(
onPressed: () async {
// status=true
final value = await FirebaseFirestore.instance
.collection(widget.symbol '_Live')
.doc("data")
.get();
final data = value.data();
final strategies =
data!['strategies'] as List<Map<String, dynamic>>;
final strategy = strategies.firstWhere(
(item) => item['strategyName'] == strategyName,
orElse: () => Map());
strategy['status'] = true;
await FirebaseFirestore.instance
.collection(widget.symbol '_Live')
.doc("data")
.update(data);
},
child: Text("Start"),
),
顯然,這行不通,因為在這里我只是在本地更改它,即不使用 Firestoreupdate方法實際更改欄位。但我對如何更新該嵌套欄位感到困惑。
任何線索/幫助將不勝感激!
編輯:
- 我按照你說的做了并編輯了我的答案,但現在錯誤消失了,但似乎沒有任何效果,即在 firestore 中,資料檔案沒有變化。
ERROR:Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>' in type cast
uj5u.com熱心網友回復:
您需要在value本地更新地圖,然后將其存盤回來:
final value = await FirebaseFirestore.instance
.collection(symbol '_Live')
.doc("data")
.get();
final data = value.data();
final strategies =
data!['strategies'].map((item) => item as Map<String, dynamic>).toList();
final strategy = strategies.firstWhere(
(item) => item['strategyName'] == strategyName,
orElse: () => Map());
strategy['status'] = toggleValue;
await FirebaseFirestore.instance
.collection(symbol '_Live')
.doc("data")
.update(data);
關鍵是要存盤整個value.
作者編輯:只需要將每個元素映射到Map<String, dynamic>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342566.html
標籤:扑 镖 谷歌云firestore
上一篇:Dart:如何正確處理空安全?
下一篇:在顏色屬性中動態添加字串值
