3

A common thing I do in my web application is request a resource from the server and handle it as a Map in dart.

import 'dart:convert';

const String sampleJSON = '''
{
    "member": {
        "meaningOfLife": 42
    }
}
''';

Map<String, dynamic> getResource() {
  // do some magic
  return JSON.decode(sampleJSON);
}

I live with the assumption that all keys in a JSON decoded Map will be Strings but obviously I have no clue of the value's type. In checked mode this worked fairly well.

Analysis in strong mode to the code above will tell me: Unsound implicit cast from dynamic to Map<String, dynamic>

Question:

What is a good strategy to handle such cast warnings?

Questionable options 1:

Map getResource() {
  // do some magic
  return JSON.decode(sampleJSON);
}

Later this could be a problem: Iterable<String> keys = getResource().keys will give a warning.

Questionable option 2:

Map<String, dynamic> getResource() {
  // do some magic
  return new Map<String, dynamic>.from(JSON.decode(sampleJSON));
}

Does it not degrade performance much? And I will still get a warning for Map<String, dynamic> meaning = getResource()["member"];

Thanks for the advice.

Daniel V.
  • 1,138
  • 1
  • 9
  • 15

1 Answers1

5

If you know the type then just make it explicit

return JSON.decode(sampleJSON) as Map<String,dynamic>;

The Flutter team forbids the use of as because it introduces a runtime check and has performance implications. If it is relevant, depends on your requirements.

Alternatively, you can just silence the warning (might not yet work in your Dart version)

// ignore: STRONG_MODE_DOWN_CAST_COMPOSITE
return JSON.decode(sampleJSON);

See also Suppress hint about use of protected member

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567