在 Dart 中使用模式解构时如何转换数据?

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

我遇到了从 API 接收的数据的类型错误。为了清楚地模拟这个问题,我在下面提供了一个代码示例:

List<dynamic> dat2 = [{"id1": 'food',},{'id2': "car"}];
var data = {"types": dat2, "clientId": "Id"};

代码:

         if (data case {
                   //how I can cast it to List<Map<String, dynamic>> here without extra code?
                  "types": List<Map<String, dynamic>> types,
                  "clientId": String clientId}) 
                       {
                          debugPrint('types:$types, clientId: $clientId');
                        } else {
                           debugPrint('Error');
                                }

错误发生在“types”参数中。我怎样才能在 if 条件下正确地转换它来解决这个问题?

flutter dart casting pattern-matching typeerror
1个回答
0
投票

试试这个!

List<dynamic> dat2 = [
  {
    "id1": 'food',
  },
  {'id2': "car"}
];
dynamic data = {"types": dat2, "clientId": "Id"};

if (data is Map<String, dynamic> &&
    data.containsKey("types") &&
    data["types"] is List<dynamic>) {
  List<Map<String, dynamic>> types = [];
  for (var item in data["types"]) {
    if (item is Map<String, dynamic>) {
      types.add(Map<String, dynamic>.from(item));
    }
  }
  String clientId = data["clientId"];
  debugPrint('types:$types, clientId: $clientId');
} else {
  debugPrint('Error');
}
© www.soinside.com 2019 - 2024. All rights reserved.