I’m working on a Dart project where I need to call a JavaScript function that takes a typed array as an argument. I’ve tried using js.array to convert a Uint8Array, but it’s not working as expected. Here’s what I’ve attempted:
var myData = [1, 2, 3, 4, 5];
var typedArray = Uint8Array.fromList(myData);
var jsArray = js.array(typedArray);
When I pass jsArray to the JavaScript function, it doesn’t recognize it as a typed array. Does anyone know the correct way to convert a Dart typed array to a JavaScript typed array using js-interop? I’m looking for a solution that preserves the typed array structure when it reaches the JavaScript side. Any help would be appreciated!
I’ve dealt with this exact problem in a recent project. The key is to use js.typed.Uint8Array.from() instead of js.array(). Here’s what worked for me:
var myData = [1, 2, 3, 4, 5];
var dartTypedArray = Uint8List.fromList(myData);
var jsTypedArray = js.typed.Uint8Array.from(dartTypedArray);
This approach creates a JavaScript Uint8Array directly from your Dart Uint8List. It maintains the typed array structure and should be recognized correctly by your JavaScript function.
One thing to watch out for: make sure your JavaScript function is actually expecting a Uint8Array and not some other type of typed array. If it’s expecting a different type, you might need to adjust the js.typed.* class you’re using accordingly.
Also, don’t forget to import the necessary js libraries in your Dart file:
import 'dart:js_util' as js_util;
import 'package:js/js.dart' as js;
This method has been reliable for me across different browsers and setups. Let me know if you run into any issues!
I’ve encountered this issue before in a cross-platform project. The solution that worked for me was using js.typed.Uint8Array.new(). Here’s how you can modify your code:
import 'package:js/js.dart' as js;
var myData = [1, 2, 3, 4, 5];
var typedArray = Uint8List.fromList(myData);
var jsTypedArray = js.typed.Uint8Array.new(typedArray.length);
for (var i = 0; i < typedArray.length; i++) {
jsTypedArray[i] = typedArray[i];
}
This approach creates a new JavaScript Uint8Array and populates it with your Dart data. It preserves the typed array structure and should be compatible with your JavaScript function. Remember to test thoroughly, as js-interop can sometimes be tricky depending on your specific setup and environment.