Dart object to native – UnimplementedError: structured clone of other type

Issue

Integrating a dart web app with the browser history, I want to push a dart object to the window.history stack.

Dart object.

class AppState {
  final int index;

  AppState(this.index){
  }
}

Api
https://api.dartlang.org/stable/1.15.0/dart-html/History/pushState.html

It works with e.g. a Map toMap() method, together with a matching factory constructor, but this is the brute force way. Just relying on the dart framework gives the stackdump below, which indicates that AppState misses some serialization method. Anyone know which?

Uncaught Unhandled exception:
UnimplementedError: structured clone of other type
#0      _StructuredClone.walk (file:///mnt/data/b/build/slave/dartium-lucid64-full-stable/build/src/dart/sdk/lib/html/html_common/conversions.dart:136)
#1      _StructuredClone.convertDartToNative_PrepareForStructuredClone (file:///mnt/data/b/build/slave/dartium-lucid64-full-stable/build/src/dart/sdk/lib/html/html_common/conversions.dart:151)
#2      convertDartToNative_PrepareForStructuredClone (file:///mnt/data/b/build/slave/dartium-lucid64-full-stable/build/src/dart/sdk/lib/html/html_common/conversions_dartium.dart:4)
#3      convertDartToNative_SerializedScriptValue (file:///mnt/data/b/build/slave/dartium-lucid64-full-stable/build/src/dart/sdk/lib/html/html_common/conversions.dart:33)
#4      History.pushState (dart:html:19793)
#5      AppHistoryCtrl.pushState (package:mintest/app_history_ctrl.dart:35:20)

Solution

That’s what’s supposed to happen. In order to get into history, it gets serialized through the structured clone algorithm, which is specified. That doesn’t know how to deal with arbitrary Dart objects. For example, if we push something into history that way, some JavaScript code might take it out, and that can’t handle arbitrary Dart objects. So yes, it needs to be converted into a Map, or some other structure that the structured clone algorithm understands.

Answered By – Alan Knight

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *