DEV Community

Crizant Lai
Crizant Lai

Posted on • Originally published at Medium

Flutter: How to work with JSONs like a PRO

Before being a Flutter developer, I came from the JavaScript world. One thing I missed the most is the mighty JavaScript packages on npm, especially lodash and ramda.

When developing Flutter applications, we often need to parse JSON objects from API responses, then access or manipulate them accordingly. Sadly dart language’s support for Map objects is not very rich, therefore I created this package: map_enhancer.

Usage

import 'package:map_enhancer/map_enhancer.dart';

void main() {
  final Map peter = {
    'name': {
      'firstName': 'Peter',
      'lastName': 'Petrelli',
    },
    'age': 29,
  };

  print(
    peter.getIn(['name', 'firstName']),
  );
  // Output: Peter

  // or if you prefer the JSON "dot notation":
  print(
    peter.getIn('name.firstName'.split('.')),
  );
  // Output: Peter

  // call with default value:
  print(
    peter.getIn(
      'name.nickName'.split('.'),
      defaultValue: 'Pete',
    ),
  );
  // Output: Pete

  peter.setIn(['ability'], 'Empathic mimicry');
  print(peter['ability']);
  // Output: Empathic mimicry

  peter.unsetIn(['name', 'lastName']);
  print(peter['name']['lastName']);
  // Output: null

  print(peter.hasIn(['name', 'nickname']));
  // Output: false
}

Actually this package is not restricted to Flutter and JSON(Map) objects, you may use it in any dart projects, or on any dart’s native Map objects.

And that’s it. Visit pub.dev to install this package, or submit issues/pull requests on GitHub.

Top comments (0)