
我的模型中有開始和結束欄位作為時間戳,但出現此錯誤。當我在我的模型中將開始和結束定義為 var 時,我不明白。
Unhandled Exception: type 'Null' is not a subtype of type 'Timestamp'
模型:
import 'package:cloud_firestore/cloud_firestore.dart';
class Event {
String eid;
String title;
String location;
Timestamp start;
Timestamp end;
String instructor;
String image;
String description;
Event({
required this.eid,
required this.title,
required this.location,
required this.start,
required this.end,
required this.instructor,
required this.image,
required this.description
});
factory Event.fromMap(Map<String, dynamic>? map) {
return Event(
eid: map?['eid'] ?? 'undefined',
title: map?['title'] ?? 'undefined',
location: map?['location'] ?? 'undefined',
start: map?['starts'],
end: map?['ends'],
instructor: map?['instructor'] ?? 'undefined',
image: map?['image'] ?? 'undefined',
description: map?['description'] ?? 'undefined'
);
}
uj5u.com熱心網友回復:
您正在獲取和的null值,您需要像其他變數一樣為它們定義一個默認值:startend
factory Event.fromMap(Map<String, dynamic>? map) {
return Event(
eid: map?['eid'] ?? 'undefined',
title: map?['title'] ?? 'undefined',
location: map?['location'] ?? 'undefined',
start: map?['starts'] ?? Timestamp(0, 0),//<--- add this
end: map?['ends'] ?? Timestamp(0, 0),//<--- add this
instructor: map?['instructor'] ?? 'undefined',
image: map?['image'] ?? 'undefined',
description: map?['description'] ?? 'undefined'
);
}
uj5u.com熱心網友回復:
start: map?['starts'],
end: map?['ends'],
您在這里所做的是將開始/結束引數設定為來自 firestore 的地圖,但如果檔案沒有該欄位,則您沒有回退,它會回傳null.
執行以下任一操作:
- 向引數添加回退值,例如當前時間戳或其他一些:
start: map?['starts'] ?? Timestamp.now(),
end: map?['ends'] ?? Timestamp.now(),
- 如果您希望那里的內容可能為空,請使時間戳可為空:
class Event {
// ...
Timestamp? start;
Timestamp? end;
uj5u.com熱心網友回復:
這是因為您沒有給出默認值(與您對所有其他變數所做的方式相同):
?? 'undefined'
一種可能的解決方案是允許null值...只需添加?兩個變數定義,如下所示:
class Event {
String eid;
String title;
String location;
Timestamp? start; // *** change 1
Timestamp? end; // *** change 2
String instructor;
String image;
String description;
如果這不起作用,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/537211.html
標籤:谷歌云集体 扑火力基地镖google-cloud-firestore飞镖空安全
上一篇:按日期顫動過濾器串列
