flutter 将Firebase嵌套到dart模型的HttpsCallableResult

imzjd6km  于 2023-01-21  发布在  Flutter
关注(0)|答案(1)|浏览(111)

我试图从云函数中获取一些数据并将其分配给模型。但是我无法使用嵌套数据,我得到以下错误:_TypeError (type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>')
我收到的数据如下所示:

{
  "answer": "Some optional answer",
  "error": "Some optional error",
   "usage": { "prompt_tokens": 32, "completion_tokens": 40, "total_tokens": 72 }
}

当我收到数据时,我尝试将其分配给一个模型:

final HttpsCallableResult result = await functions
          .httpsCallable('askHW')
          .call({'question': userQuestion});
      return HWResponse.fromJson(result.data);

HW响应:

class HWResponse {
  final String answer;
  final String error;
  final HWUsage usage;

  HWResponse({this.answer = '', this.error = '', required this.usage});

  factory HWResponse.fromJson(Map<String, dynamic> json) => HWResponse(
        answer: json.containsKey('answer') ? json['answer'] as String : '',
        error: json.containsKey('error') ? json['error'] as String : '',
        usage:
            json["usage"] == null ? HWUsage() : HWUsage.fromJson(json["usage"]),
      );

  Map<String, dynamic> toJson() => {
        "answer": answer,
        "error": error,
        "usage": usage.toJson(),
      };
}

class HWUsage {
  final int promptTokens;
  final int completionTokens;
  final int totalTokens;

  HWUsage({
    this.promptTokens = 0,
    this.completionTokens = 0,
    this.totalTokens = 0,
  });

  factory HWUsage.fromJson(Map<String, dynamic> json) => HWUsage(
        promptTokens: json.containsKey('prompt_tokens')
            ? json['prompt_tokens'] as int
            : 0,
        completionTokens: json.containsKey('completion_tokens')
            ? json['completion_tokens'] as int
            : 0,
        totalTokens:
            json.containsKey('total_tokens') ? json['total_tokens'] as int : 0,
      );

  Map<String, dynamic> toJson() => {
        "prompt_tokens": promptTokens,
        "completion_tokens": completionTokens,
        "total_tokens": totalTokens,
      };
}
iklwldmw

iklwldmw1#

在嵌套字段的HWResponse中使用Map<String, dynamic>.from('json['usage]')似乎是正确的方法,为了避免任何错误,我还使用了json.containsKey('usage')来确保嵌套字段usage确实存在。

usage: json.containsKey('usage')
  ? HWUsage.fromJson(Map<String, dynamic>.from(json['usage']))
  : HWUsage(),

相关问题