Parse dynamic as int or fallback to a default value

1,593

You can abstract the operation into a function like

int intOrStringValue(dynamic o) {
  if (o is String) o = int.tryParse(o);
  return o ?? 0;
}

or

int intOrStringValue(dynamic o) =>
    (o is String ? int.tryParse(o) : o) ?? 0;

It gets more readable when you don't repeat the map['maxposts'] expression throughout the logic.

Share:
1,593
Magnus
Author by

Magnus

I have delivered value. But at what cost? Bachelor of Science degree in Computer Engineering. ✪ Started out on ATARI ST BASIC in the 1980's, writing mostly "Look door, take key" type games.    ✪ Spent a few years in high school writing various small programs for personal use in Delphi.    ✪ Learned PHP/SQL/HTML/JS/CSS and played around with that for a few years.    ✪ Did mostly Android and Java for a few years.    ✪ Graduated from Sweden Mid University with a BSc in Computer Engineering. At this point, I had learned all there was to know about software development, except where to find that darn "any" key...    ✪ Currently working with Flutter/Dart and Delphi (again).   

Updated on December 09, 2022

Comments

  • Magnus
    Magnus over 1 year

    I have a map with dynamic values, one of which can be an int, string or null (i.e. non-existing key).

    I want to store this value in an int variable. The parsing I came up with ended up being quite cumbersome:

    Map<String, dynamic> map = {'maxposts': null}; // or 23 or '42'
    
    // Try to parse an int value or fall back to 0
    int maxposts = (map['maxposts'] is int) 
        ? map['maxposts'] 
        : int.tryParse(map['maxposts'] ?? '0') ?? 0;
    

    Is there a nicer way of doing such a "try-fallback" parsing?

    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      I don't think there is.