flutter web_在Flutter Web中使用JavaScript代码

本文介绍了如何在Flutter Web应用中集成和使用JavaScript代码,通过实例展示了跨平台开发中的技术融合。
摘要由CSDN通过智能技术生成

flutter web

When building cross-platform applications that can run on web, mobile and desktop, we often don’t need to access the underlying platform — we are either showing static data or we are communicating with a backend server to post and display newdata.

在构建可在Web,移动和桌面上运行的跨平台应用程序时,我们通常不需要访问底层平台-我们要么显示静态数据,要么与后端服务器通信以发布和显示新数据。

However, there are cases in which we need to retrieve some information about the platform — device’s specifications, location or hardware such as camera and sensors — or even access a specific native library or API, which requires us to communicate with the platform’s native code.

但是,在某些情况下,我们需要检索有关平台的某些信息(设备的规格,位置或硬件,例如摄像头和传感器),甚至访问特定的本机库或API,这需要我们与平台的本机代码进行通信。

With Android and iOS we use Platform Channels to send and receive messages from the native platform, and we can use PlatformViews to display native UI views on Flutter. But how we can do it in Flutter Web?

在Android和iOS上,我们使用平台通道从本机平台发送和接收消息,并且可以使用PlatformViews在Flutter上显示本机UI视图。 但是我们如何在Flutter Web中做到这一点?

JavaScript和Dart (JavaScript and Dart)

Before Flutter was revealed to the public, Dart was used to build web apps (as you can see in this article from 2013 — Develop modern web apps with Dart by Seth Ladd), which was possible due to two of its features:

在Flutter公开露面之前,Dart曾被用来构建Web应用程序(如您在2013年的这篇文章中所见-使用Seth Ladd的Dart开发现代Web应用程序),这是有可能的,这是由于其两个功能:

  • The ability to compile Dart code to JavaScript;

    编译能力 Dart代码转换为JavaScript ;

  • JavaScript-Dart interoperability via the js package that allows us to call Dart code in JavaScript.

    JavaScript-Dart互操作性 通过js允许我们用JavaScript调用Dart代码

This means that we have a direct way to communicate with JavaScript without the need of PlatformChannels

这意味着我们无需使用PlatformChannels就可以直接与JavaScript通信

To use the js package, we must declare in a separate file the functions in JavaScript that we need to call with the help of the @JS annotation.

要使用js包,我们必须在单独的文件中声明需要在@JS注释的帮助下调用的JavaScript函数。

As an example, let’s look at the documentation and see how it is possible to use JSON.stringify in Dart:

例如,让我们看一下文档,看看如何在Dart中使用JSON.stringify

@JS()
library stringify;


import 'package:js/js.dart';


// Calls invoke JavaScript `JSON.stringify(obj)`.
@JS('JSON.stringify')
external String stringify(Object obj);
  • The library statement has the @JS() annotation, followed by the js.dart import statement.

    library语句具有@JS()批注,后跟js.dart导入语句。

  • @JS is used to specify which function we are calling, in this case, JSON.stringify . Note that the declared function has no body and is external, which you can read more about in this

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值