Search code examples
fluttercasting

Flutter 2: Cast List<dynamic> or Map<dynamic> on what you desire


I had troubles regarding my application to cast my variables into certain types.

For example:

Map<dynamic> into Map<String, List<Map<String, dynamic>>>?

How would you do ?


Solution

  • First I initialise my variables:

    Map<String, List<Map<String, dynamic>>>? test = {
        [{'test': 'test'}]
    }
    

    Here I want to perform a deepcopy so I use jsonEncode jsonDecode which will clone my variable and cast my clone into a Map<dynamic>.

    jsonDecode(jsonEncode(test))
    

    Next I want to cast my result into a MapEntry<String, List<dynamic>>.

    (jsonDecode(jsonEncode(test)) as Map).map((key, value) => MapEntry(key, value))
    

    Finally I want to cast my value (List<dynamic>) into a List<Map<String, dynamic>>

    Map<String, List<Map<String, dynamic>>>? result = (jsonDecode(jsonEncode(test)) as Map).map((key, value) =>
            MapEntry(key, (value as List).map((e) => e as Map<String, dynamic>).toList())
    

    Here the variable has now a type of: Map<String, List<Map<String, dynamic>>>?

    So this is the answer for performing a deep copy with a deep casting.