我正在從 Firestore 讀取資料。我收到一條錯誤訊息type 'Timestamp' is not a subtype of type 'String' in type cast,因此我將createDate下面的行更改為使用.toString()而不是做as String。這解決了問題,但為什么會這樣呢?
Notification.fromJson(Map<dynamic, dynamic>? json): //Transform JSON into Notification
createDate = (json?['createDate']).toString(), //This works
modifiedDate = json?['modifiedDate'] as String; //This gives the error: 'type 'Timestamp' is not a subtype of type 'String' in type cast'
這兩個欄位的格式都是October 5, 2022 at 10:49 PM UTC-5.
uj5u.com熱心網友回復:
json?['createDate']是一個Timestamp型別的物件,它只包含描述時間點的數字。正如您從 API 檔案中看到的,它有一個名為toString的方法,該方法知道如何將其轉換為格式化的日期字串。由于 Timestamp 不是 String 的子類,Dart 不允許將其強制轉換為一個。也許您想將其轉換為 Timestamp,因為它就是這樣?
uj5u.com熱心網友回復:
就像錯誤訊息中所說的那樣,您收到此錯誤,因為來自 json 的值的型別是 Timestamp,而不是 String。最好將createDate和modifiedDate欄位設定為Timestamp型別而不是String,因為它提供了自己的方法,使您的作業更輕松。轉換為字串(并且可能,您正在某處決議此字串)是多余的。
uj5u.com熱心網友回復:
在 Flutter 中,每個物件類都有toString()方法,它回傳一個 String 型別的值
(json?['createDate']).toString();
因此,如果您在上面撰寫該代碼,它將回傳一個 String 型別的值,然后將該值分配給createDate變數。這意味著您不分配json?['createDate'].
modifiedDate = json?['modifiedDate'] as String;
上面的那一行會出錯,因為您將該 json 分配給具有不同型別的 modifiedDate。Cast ( as) 僅在物件/變數具有相同層次結構時才有效,例如
Child child = Child();
Parent parent = child as Parent();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512568.html
