isPrimitiveType function

bool isPrimitiveType(
  1. dynamic value
)

Determines whether a given value is of a primitive type for JSON serialization.

This function checks if the provided value is a type that can be directly serialized into JSON. The types considered as primitives for this purpose are: num (which includes both int and double), bool, String, BigInt, DateTime, and Uint8List. Additionally, collections (lists, sets) exclusively containing primitives are also considered primitive.

Returns true if value is a primitive type or a collection of primitives, and false otherwise.

Example:

bool isNumPrimitive = isPrimitiveType(10); // true
bool isStringPrimitive = isPrimitiveType('Hello'); // true
bool isComplexObjectPrimitive = isPrimitiveType(MyCustomClass()); // false

Implementation

bool isPrimitiveType(dynamic value) {
  return value is num || // Includes both int and double
      value is bool ||
      value is String ||
      value is BigInt ||
      value is DateTime ||
      value is Uint8List ||
      _isCollectionOfPrimitives(value);
}