Skip to content

Map Patterns Deconstructing a Non-Existent Key Throws an Exception #3389

Closed
@aboutlan

Description

@aboutlan

Dart's Map Patterns Deconstructing a Non-Existent Key throws a "Pattern matching error", but I want the variable to be null, Does Dart's syntax support this? How can I do that?

Practical scenario: When I'm Deconstructing Json, I'm not sure if a key exists in the Json or not, and if it doesn't, it will cause the problem.

void main() {
  final userInfo = {
    "name": "Jack",
    "age": 18
  };
  // Here throws a Pattern matching error, but my expectation is that the gender variable is null, so how do I do this?
  final {"gender": gender as String?} = userInfo; 
  print(gender); 
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problemstate-duplicateThis issue or pull request already exists

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions