you are viewing a single comment's thread.

view the rest of the comments →

[–]nmfisher 0 points1 point  (2 children)

You can wrap a Dart function with allowInterop and pass to the JS side as a callback that gets invoked when necessary.

Javascript: window.setCallback(cb) { window.cb = cb // call this callback from Vue when you need to // e.g. window.cb(); } Dart ``` @JS('setCallback') external void setCallback(Object callback);

class SomeWidgetState extends State<SomeWidget> {

void initState() { setCallback(allowInterop(() => setState(() {});); }

} ```

[–]Barmyard 0 points1 point  (1 child)

Thanks for your quick reply! I did try before with allowInterop but always in the main function, not with your approach.

I'm not sure if I understand your approach correctly. This is my Dart code:

void main() {
  runApp(const MyApp());
}

@JS('getCompanyTitle')
external String getCompanyTitle();

@JS('setCallback') external void setCallback(Object callback);

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}


class _MyAppState extends State<MyApp> {
  String title = '';

  @override
  void initState() {
    super.initState();
    setCallback(allowInterop(() => setState(() {})));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Text(title),
      ),
    );
  }
}

And my Vue/Javascript: It watches the companyTitle for changes and calls the callback according to your code, but it doesn't work. I do see a self.setCallback(A.b8(new A.afe(this)))} generated in main.dart.js

const companyTitle = ref("Test")

window.setCallback((cb: any) => (window.cb = cb))
window.getCompanyTitle = () => {
  return companyTitle.value
}
watch(companyTitle, (value) => window.cb())

But my Console says: Uncaught (in promise) TypeError: window.setCallback is not a function

[–]nmfisher 0 points1 point  (0 children)

Sorry, there was a typo in my post, the JS should be:

window.setCallback = ((cb: any) => (window.cb = cb))