Issue
I have the code
if (WORDLIST[language]==null) throw new Exception("Invalid Language");
List<String> wordlist = WORDLIST[language];
the compiler says
Error: A value of type 'List?' can't be assigned to a variable of type 'List' because 'List?' is nullable and 'List' isn't.
However its both not possible in my code for language to be set to a value that is not valid and just to be safe there is the exception thrown if it gets called somewhere without checking the language exists. How can I get the compiler to recognize this is valid?
Full Code is here(though the exception was added afterwards to try and handle new compiler): https://github.com/mctrivia/bip39-multi/blob/mctrivia-patch-1/lib/src/bip39_multi_base.dart#L80
Solution
Map.operator []
returns a nullable type, period. The compiler doesn't know what WORDLIST[language]
will return at runtime; it doesn't know that WORDLIST
isn't some Map
implementation that returns different values each time operator []
is called. This is the same reason why only local variables can be type promoted.
The typical ways to fix this are:
- Use
!
to force the result to be non-nullable:if (WORDLIST[language]==null) throw new Exception("Invalid Language"); List<String> wordlist = WORDLIST[language]!;
- Use a local variable:
Sincevar result = WORDLIST[language]; if (result == null) throw new Exception("Invalid Language"); List<String> wordlist = result;
wordlist
is probably already a local variable, you also could just reorder your code:List<String>? wordlist = result; if (wordlist == null) throw new Exception("Invalid Language"); // wordlist is now type-promoted to be List<String>.
Answered By - jamesdlin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.