Skip to content

Converting Objects

Overview

Convert objects to various types, such as int, double, bool, String, List, Set and Map, They are handy when working with data from APIs, where you often encounter dynamic types. They offer simple and flexible methods to perform accurate type conversions. Here is a sample:

Before:

Map = {score: "12.4"};

dart
int score = double.parse(map['key']).toInt();
int score = double.parse(map['key']).toInt();

Notice that we need to parse to double first then to int.

With Package:

dart
int score = toInt(map['key']);
int score = toInt(map['key']);

Available Methods:

  • toInt() or tryToInt
  • toDouble() or tryToDouble
  • toBool() or tryToBool
  • toString1() or tryToString1
  • toList<T>() or tryToList
  • toSet<T>() or tryToSet
  • toMap<K, V>() or tryToMap

ConvertObject Methods

Typically, all the above methods calls are global ones that call the original static methods from the ConvertObject class.

so we can say:

dart
int score = toInt(map['key']); // global method
// same as
int score = ConvertObject.toInt(map['key']); // static method
int score = toInt(map['key']); // global method
// same as
int score = ConvertObject.toInt(map['key']); // static method

NOTE: when using the global methods sometimes, you might encounter conflict with some method names e.g. toList, to avoid that, consider using the static method instead e.g. ConvertObject.toList (only for the conflicted one).

Optional Parameters

Each method accepts two optional parameters: listIndex and mapKey. These parameters allow you to extract and convert specific values within a List or a Map object, respectively. For example, if you have a list of strings representing numbers, you can use the listIndex parameter to convert a particular element to an integer:

dart
dynamic dynamic1 = ['10', '20', '30'];
final int number = toInt(dynamic1, listIndex: 1); // 20
dynamic dynamic1 = ['10', '20', '30'];
final int number = toInt(dynamic1, listIndex: 1); // 20

Similarly, if you have a map of strings representing different types of values, you can use the mapKey parameter to convert a particular value to a boolean:

dart
dynamic dynamic2 = { 'name': 'John',
	                   'age': '30',
  	                 'bools': {
                       'isHuman': 'yes',
                     }
                  };
final bool isHuman = toBool(dynamic2['bools'], mapKey: 'isHuman'); // true
dynamic dynamic2 = { 'name': 'John',
	                   'age': '30',
  	                 'bools': {
                       'isHuman': 'yes',
                     }
                  };
final bool isHuman = toBool(dynamic2['bools'], mapKey: 'isHuman'); // true