让我们来深入相识一下它的运行机制。假设您正在编写一个小程序来盘算从当前时间开始一天后的时间。使用 ML Complete,您将得到下图这样迅捷的开辟体验。
△ 使用 ML Complete 编写代码的体验
△ 不使用 ML Complete 编写同样代码的体验 首先,请注意 ML Complete 会根据开辟者输入的变量名称 now 自动给出 DateTime.now() 的发起。当第一行输入完成后,请注意我们在开辟者输入第二个变量名时,也给出了 tomorrow 这个变量名发起。最后,基于 now 这个变量给出了第二个补全发起 add(…)。而在上图的非 ML Complete 体验中,我们必须手动键入 DateTime,而且在键入 tomorrow 变量名时没有补全提示,别的 now 的 add(…) 方法在推荐列表更下面的位置才出现。
如何试用 ML Complete
ML Complete 本日推出预览版。它内置于 Dart 分析器中,因此可用于所有支持 Dart 的编辑器,包罗 Android Studio、IntelliJ 和 VS Code。有关如何启用此预览功能,以及如何提供反馈和报告问题,请参阅我们的 反馈 wiki 页 。
问题反馈 wiki 页 https://github.com/dart-lang/sdk/wiki/Previewing-Dart-code-completions-powered-by-machine-learning
由于该功能仍在预览中,因此当前 Flutter 和 Dart 稳定版本中的 ML Complete 在性能体现和优化细节上会不及我们筹划推出的后续版本。因此,我们发起您试用此功能时暂时使用 Flutter dev 渠道 或 Dart dev 渠道 。
Flutter dev 渠道
https://github.com/flutter/flutter/wiki/Flutter-build-release-channels
Dart dev 渠道
https://dart.dev/tools/sdk/archive#dev-channel
dart:ffi 外部函数接口
许多开辟者要求我们为从 Dart 调用 C 代码提供更好的支持。一个非常明确的信号,是在 Flutter 问题反馈专区里 C 语言互操纵是 呼声最高的功能请求 ,得票数超过 600。这些功能请求背后有许多有趣的用例,包罗调用低级平台 API (如 stdlib.h 或 Win32 ),调用现有的跨平台库以及用 C 语言编写的实用程序 (如 TensorFlow、Realm 和 SQLite) 等。
// Load `stdlib`. On MacOS this is in libSystem.dylib. final dylib = ffi.DynamicLibrary.open('/usr/lib/libSystem.dylib'); // Look up the system function. final systemP = dylib.lookupFunction('system');
Windows 示例 https://github.com/dart-lang/samples/blob/master/ffi/system-command/windows.dart
Linux 示例 https://github.com/dart-lang/samples/blob/master/ffi/system-command/linux.dart
接下来,我们使用与特定操纵系统相关的编码对字符串参数举行编码,调用该函数,并再次释放参数内存:
// Allocate a pointer to a Utf8 array containing our command. final cmdP = Utf8.toUtf8('open http://dart.dev'); // Invoke the command. systemP(cmdP); // Free the pointer. cmdP.free();
复制代码
这段代码会执行系统下令,使用系统默认欣赏器打开 dart.dev 网页:
△ 通过 dart:ffi 使用系统 API 打开默认欣赏器
调用基于 C 的框架和组件
dart:ffi 的第二个焦点用途是调用基于 C 的框架和组件。本文前面提及过的基于 ML 的代码补全功能就是一个详细的例子!它使用 TensorFlow Lite,这是一个基于 C 的 API。使用 dart:ffi 可以让我们在需要提供代码补全的所有操纵系统上运行 TensorFlow,同时拥有原生 TensorFlow 的高性能。如果您想检察 Dart 与 TensorFlow 集成的代码,请检察 这个 repo 。
// Example: these are now valid compile-time constants. const Object i = 3; const list = [i as int]; const set = {if (list is List) ...list}; const map = {if (i is int) i: "int"};