我期待着未来。但为什么该函数会说“主体可能正常完成,导致返回‘null’,但返回类型‘FutureOr
Future<DocumentReference<Map<String, dynamic>>> duplicatePhone(
DocumentReference<Map<String, dynamic>> timerRef) async {
timerRef.get().then((DocumentSnapshot documentSnapshot) async {
Map<String, dynamic> snapshotData;
snapshotData = documentSnapshot.data() as Map<String, dynamic>;
String title = snapshotData['title'] as String;
int durationNumber = snapshotData['duration'] as int;
Duration duration = Duration(milliseconds: durationNumber);
return add(title, duration: duration);
});
}
您可以使用 try-catch 来简化您的代码:
Future<DocumentReference<Map<String, dynamic>>> duplicatePhone(
DocumentReference<Map<String, dynamic>> timerRef) async {
try {
DocumentSnapshot documentSnapshot = await timerRef.get();
if (documentSnapshot.exists) {
final snapshotData = documentSnapshot.data() as Map<String, dynamic>;
String title = snapshotData['title'] as String;
int durationNumber = snapshotData['duration'] as int;
Duration duration = Duration(milliseconds: durationNumber);
// assuming add method returns a DocumentReference
return add(title, duration: duration);
} else {
throw Exception("Document does not exist");
}
} catch (e) {
rethrow;
}
}