Is there a clean way of type casting anything to an int in dart?

Viewed 58

So I have this database that can have either a double, string, or int, and I need to cast that value to an int so it can be sorted by value.

Example:

dynamic input1 = "1";
dynamic input2 = 3;
dynamic input3 = "4.02";
dynamic input4 = 2.3;

// [1, 3, 4, 2]
List<int> output = [toInt(input1), toInt(input2), toInt(input3), toInt(input4)];

output.sort(); // [1, 2, 3, 4]

1 Answers

After a little bit of thinking, I've come up with this solution.

  int typecastToInt(dynamic x) {
    double? dX = double.tryParse(x.toString());
    if (dX != null) return dX.round();
    return 0;
  }

Also, if the value needed to be sorted in list form, you could use this:


  int compareDynamic(dynamic a, dynamic b) {
    double? dA = double.tryParse(a.toString());
    double? dB = double.tryParse(b.toString());
    
    if (dA != null && dB != null) {
      return dA.compareTo(dB);
    } else {
      // swap these values if you want NaN to be at the front of the list
      if (dA == null) return 1;
      return -1;
    }
  }

  List sortDynamic(List list) {
    List sortedList = List.from(list);
    sortedList.sort((a, b) => compareDynamic(a, b));
    return sortedList;
  }

Related