flattenDynamicTensor function

Float32List flattenDynamicTensor(
  1. Object? out
)

Flattens a nested numeric tensor (dynamic output) into a Float32List.

Supports arbitrarily nested List structures containing num leaves. Throws a StateError if an unexpected type is encountered or if out is null.

Implementation

Float32List flattenDynamicTensor(Object? out) {
  if (out == null) {
    throw TypeError();
  }
  final List<double> flat = <double>[];
  void walk(dynamic x) {
    if (x is num) {
      flat.add(x.toDouble());
    } else if (x is List) {
      for (final e in x) {
        walk(e);
      }
    } else {
      throw StateError('Unexpected output element type: ${x.runtimeType}');
    }
  }

  walk(out);
  return Float32List.fromList(flat);
}