Search code examples
flutterdarthashmap

How to tell dart to not convert map to <String, String> type and let it be <String, Object> type?


I have some data which initially is List<Map<String, String>> but in future in some methods calls I have to assign those Map<String, String> elements an <String, dynamic> values. Here is some dart code that shows my intention :

class MyClass {
  String ageGroup = 'some';
  MyClass({required this.ageGroup});
}

void main() {
  var data = [
    {
      'name': 'john',
      'userName': 'john',
    },
    {
      'name': 'john1',
      'userName': 'john1',
    },
  ];

  // JsLinkedHashMap<String, String> in dartpad
  print(data[0].runtimeType);
  
  // after some while
  // throws an error
  data[0]['ageGroup'] = MyClass(ageGroup: 'something');
}

data[0]['ageGroup'] assignment gives me error like this : Error: A value of type 'MyClass' can't be assigned to a variable of type 'String'.

How should I let know dart that don't convert this maps to <String, String> and let it be <String, dynamic> as in future Objects would be the values too.

I have found 1 workaround but I don't want to use it :

void main() {
  var data = [
    {
      'something_random': 123,
      'name': 'john',
      'userName': 'john',
    },
    {
      'something_random': 123,
      'name': 'john1',
      'userName': 'john1',
    },
  ];
  
  print(data[0].runtimeType);
  
  data[0]['ageGroup'] = MyClass(ageGroup: 'something');
}

This works well but I don't want to use it like this....are there any other ways... I have tried .cast<>() and another type castings but still of no use.


Solution

  • By default Dart infers the type of you data literal map.

    In your first example there is only String as values so it infers the type List<Map<String, String>>. In the last snippet it infers List<Map<String, Object>> because there are Strings and ints in values of maps.

    You can force the type of data by 2 ways:

    var data = <Map<String, dynamic>>[...]; // force type of list literal
    
    // or
    
    List<Map<String, dynamic>> data = [...]; // directly type data