为什么我的函数正常显示主体已完成,导致返回 null?

问题描述 投票:0回答:1

我期待着未来。但为什么该函数会说“主体可能正常完成,导致返回‘null’,但返回类型‘FutureOr>>’可能是不可为空的类型。 尝试在末尾添加 return 或 throw 语句。'

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);

      
    });
  }
flutter firebase
1个回答
0
投票

您可以使用 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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.