For example, I have Map<int, int> m;. Then I can write down m['hello'] without any compile-time error, but of course, cannot find any element at runtime. I hope it will produce an error (or warning) at compile-time or lint time.

This is a big problem in many cases. For example, when I refactor Map<A, int> m into Map<B, int> m, I want to have compile-time errors for all accesses like m[some_var_of_type_A], instead of no compile-time errors and suddenly it explodes at runtime. As another example, the de-serialized JSON is of type Map<String, ...> but the key is actually a int. So it is tempting to do var userId=42; deserializedJson[userId] but only to find errors. Actually need to do deserializedJson[userId.toString()].

You know, dart's type system is so strong (even null safe!), and I really enjoy it since it catchs a LOT of bugs at compile-time. So I hope this problem can also be addressed at compile-time.

Thanks for any suggestions!


Solution 1: nicks101

NOTE:

The original answer was wrong and has been edited to:

  • point out the right/better answer
  • explain why the original answer was wrong

Thank you @jamesdlin for pointing this out.

Better answer

As pointed by @jamesdlin in his answer, the lint rule mentioned in the question has been requested in the flutter Github issues, and not in production yet.

Original Answer (wrong but kind of related to the question)

Why it is wrong:

The question was asking about the lint rule when using an index of Map. The answer however gave the lint rule about initializing a map using the wrong index (By the wrong index, I mean different data type).

Below is the answer:


There is a lint rule for this.

For example, if you define a Map like this ->

final Map<String, String> m = {
    1: 'some random value',
};

It shows an error right away and this won't compile. This is the error ->

Error: A value of type 'int' can't be assigned to a variable of type 'String'.
    1: 'error because index is of type String but assigned value is of type int',
    ^
Error: Compilation failed.

See the official docs where this lint rule, map_key_type_not_assignable is defined.

I have tested this in dartpad and vs code. Both IDEs show this error.

There could be some issues in your IDE configuration if you're not seeing this lint error.
As for your question, there is already a lint rule for this as explained above.


Solution 2: jamesdlin

There currently is no lint to warn about doing lookups on a Map with arguments of the wrong type. This has been requested in https://github.com/dart-lang/linter/issues/1307.

Also see https://github.com/dart-lang/sdk/issues/37392, which requests a type-checked alternative to Map.operator []. In the meantime, Dart's extension mechanism allows anyone to easily add such an alternative themselves. For example, package:basics provides a type-checked Map.get extension.