[英]insert value at specific index in empty list dart
我想在空列表 dart 中的特定索引處添加元素,如下所示
List values = List();
values[87] = {'value': 'hello'};
當我嘗試運行此代碼時,它顯示此錯誤
Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 87
解決方法是設置列表長度List values = List(100);
但問題是我不知道長度,因為索引是 id,它可以是 87 或 1523....所以我不能設置長度。
另一種解決方案是使用final sparseList = SplayTreeMap<int, dynamic>();
並插入元素sparseList[87] = {'value': 'hello'};
SplayTreeMap 的問題是我無法對此類列表執行 jsonencode 或 json.encode,它顯示此錯誤消息
Unhandled Exception: Converting object to an encodable object failed: Instance of 'SplayTreeMap<int, dynamic>'
問題:
1- 如何在 dart 的空列表中的特定索引處設置元素?
2-如何 json 編碼 SplayTreeMap 列表以將其發送到服務器到 php 文件。
謝謝
我想在空列表 dart 中的特定索引處添加元素,如下所示
一種方法是在必要時將便利的 function 到 append 虛擬元素添加到List
中。
extension ListFiller<T> on List<T> {
void fillAndSet(int index, T value) {
if (index >= this.length) {
this.addAll(List<T>.filled(index - this.length + 1, null));
}
this[index] = value;
}
}
void main() {
var list = <String>[];
list.fillAndSet(3, 'world');
list.fillAndSet(2, 'hello');
print(list); // Prints: [null, null, hello, world]
}
SplayTreeMap 的問題是我無法對此類列表執行 jsonencode 或 json.encode
jsonEncode
文檔狀態(強調添加):
If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys ), ...
所以jsonEncode
對於SplayTreeMap<int, dynamic>
失敗的原因不是因為它是SplayTreeMap
而不是Map
/ LinkedHashMap
而是因為你的鍵不是String
。 ( jsonEncode
SplayTreeMap<String, dynamic>
上的 jsonEncode 應該可以工作。)您可以在編碼時轉換SplayTreeMap<int, dynamic>
:
final sparseList = SplayTreeMap<int, dynamic>();
...
var encoded = jsonEncode(<String, dynamic>{
for (var mapEntry in sparseList.entries)
mapEntry.key.toString(): mapEntry.value,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.