如何将Map <String,dynamic>转换为Map <String,List <int >>?

时间:2020-03-13 09:00:48

标签: flutter dart

我正在尝试从Firebase文档中获取一个对象,该对象最初是Map<String,List<int>>,现在在文档中是Map<String, dynamic>。但是当我使用.from()时:

Map<String,List<int>> schedule = Map<String,List<int>>.from(snapshot.data['schedule'])

Unhandled Exception: type '_InternalLinkedHashMap<String, List<dynamic>>' is not a subtype of type 'Map<String, List<int>>'

2 个答案:

答案 0 :(得分:0)

Map<String, List<int>> schedule = snapshot.data['schedule'].map(
    (k, v) => MapEntry(
      k,
      (v as List<dynamic>).cast<int>(),
    ),
  );

答案 1 :(得分:0)

您可以做一些事情。

首先,您可以在提取每个值时对它们进行延迟转换:

Auth = new OAuth2Authenticator(
             Configuration.ClientId,
             string.Empty,
             "https://www.googleapis.com/auth/contacts",
             new Uri("https://accounts.google.com/o/oauth2/v2/auth"),
             new Uri(Configuration.RedirectUrl),
             new Uri("https://www.googleapis.com/oauth2/v4/token"),
             isUsingNativeUI: true);

            var viewController = Auth.GetUI();
            PresentViewController(viewController, true, null);

            Auth.Completed += Auth_Completed;
            Auth.Error += Auth_Error;



 private void Auth_Error(object sender, AuthenticatorErrorEventArgs e)
        {

        }



 private  void  Auth_Completed(object sender, AuthenticatorCompletedEventArgs e)
        {

            // SFSafariViewController doesn't dismiss itself
            DismissViewController(true, null);

            if (e.IsAuthenticated)
            {
            }
     }

Map<String, List<int>> schedule = (snapshot.data['schedule'] as Map<String, dynamic>).cast<String, List<int>(); 操作包装原始地图,并在每次访问时进行类型检查。

或者您可以创建一个新地图:

cast

这将创建一个新的var schedule = <String, List<int>>{... snapshot.data['schedule']}; ,其键和值与时间表相同,并在创建地图时检查类型。