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 thejs.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 isexternal
, which you can read more about in this