[英]Dart HashMap initial value
我在final HashMap
的 HashMap,我怎樣才能得到它的默認值?
class RoomsState {
final HashMap<int, int> myMap;
RoomsState({
this.myMap= const {}
});
}
因為const {}
是Map
而不是HashMap
我不能這樣做,而且HashMap
不是 const 構造函數
不確定這是否是唯一的方法,但它是一種選擇:
import 'dart:collection';
class RoomsState {
final HashMap<int, int> myMap;
RoomsState({
HashMap<int, int>? myMap
}) : this.myMap = myMap ?? HashMap();
}
myMap
參數在這里可以為空,因為我們使用null
值來識別我們是否有任何參數。
您可以在構造函數中期望 Map ,然后在初始化程序中將其轉換為 HashMap 。
class RoomsState {
final HashMap<int, int> myMap;
RoomsState({
Map<int, int> map = const {},
}) : myMap = HashMap.from(map);
}
HashMap
of
構造函數創建了一個HashMap
,其中包含 other 的所有鍵/值對。 檢查此以供參考。
例子:
HashMap<String, String> englishToFrench = HashMap.of({
"go": "aller",
"buy": "acheter",
"sleep": "dormir",
});
使用示例:
void main() {
print(englishToFrench["go"]);
}
Output:
aller
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.