本节主要介绍原生和Flutter之间如何共享图像,以及如何在Flutter中嵌套原生组件。

Texture(示例:使用摄像头)

前面说过Flutter本身只是一个UI系统,对于一些系统能力的调用我们可以通过消息传送机制与原生交互。但是这种消息传送机制并不能覆盖所有的应用场景,比如我们想调用摄像头来拍照或录视频,但在拍照和录视频的过程中我们需要将预览画面显示到我们的Flutter UI中,如果我们要用Flutter定义的消息通道机制来实现这个功能,就需要将摄像头采集的每一帧图片都要从原生传递到Flutter中,这样做代价将会非常大,因为将图像或视频数据通过消息通道实时传输必然会引起内存和CPU的巨大消耗!为此,Flutter提供了一种基于Texture的图片数据共享机制。
Texture可以理解为GPU内保存将要绘制的图像数据的一个对象,Flutter engine会将Texture的数据在内存中直接进行映射(而无需在原生和Flutter之间再进行数据传递),Flutter会给每一个Texture分配一个id,同时Flutter中提供了一个Texture组件,Texture构造函数定义如下:

  1. const Texture({
  2. Key key,
  3. @required this.textureId,
  4. })

Texture 组件正是通过textureId与Texture数据关联起来;在Texture组件绘制时,Flutter会自动从内存中找到相应id的Texture数据,然后进行绘制。可以总结一下整个流程:图像数据先在原生部分缓存,然后在Flutter部分再通过textureId和缓存关联起来,最后绘制由Flutter完成。
如果我们作为一个插件开发者,我们在原生代码中分配了textureId,那么在Flutter侧使用Texture组件时要如何获取textureId呢?这又回到了之前的内容了,textureId完全可以通过MethodChannel来传递。
另外,值得注意的是,当原生摄像头捕获的图像发生变化时,Texture 组件会自动重绘,这不需要我们写任何Dart 代码去控制。

Texture用法

如果我们要手动实现一个相机插件,和前面几节介绍的“获取剩余电量”插件的步骤一样,需要分别实现原生部分和Flutter部分。考虑到大多数读者可能并非同时既了解Android开发,又了解iOS开发,如果我们再花大量篇幅来介绍不同端的实现可能会没什么意义,另外,由于Flutter官方提供的相机(camera)插件和视频播放(video_player)插件都是使用Texture来实现的,它们本身就是Texture非常好的示例,所以在本书中将不会再介绍使用Texture的具体流程了,读者有兴趣查看camera和video_player的实现代码。下面我们重点介绍一下如何使用camera和video_player。

相机示例

下面我们看一下camera包自带的一个示例,它包含如下功能:

  1. 可以拍照,也可以拍视频,拍摄完成后可以保存;排号的视频可以播放预览。
  2. 可以切换摄像头(前置摄像头、后置摄像头、其它)
  3. 可以显示已经拍摄内容的预览图。

下面我们看一下具体代码:

  1. 首先,依赖camera插件的最新版,并下载依赖。

    1. dependencies:
    2. ... //省略无关代码
    3. camera: ^0.5.2+2
  2. 在main方法中获取可用摄像头列表。

    1. void main() async {
    2. // 获取可用摄像头列表,cameras为全局变量
    3. cameras = await availableCameras();
    4. runApp(MyApp());
    5. }
  3. 构建UI。现在我们构建如图12-4的测试界面:
    Texture和PlatformView - 图1

下面是完整的代码:

  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // ignore_for_file: public_member_api_docs
  5. import 'dart:async';
  6. import 'dart:io';
  7. import 'package:camera/camera.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:path_provider/path_provider.dart';
  10. import 'package:video_player/video_player.dart';
  11. class CameraExampleHome extends StatefulWidget {
  12. @override
  13. _CameraExampleHomeState createState() {
  14. return _CameraExampleHomeState();
  15. }
  16. }
  17. /// Returns a suitable camera icon for [direction].
  18. IconData getCameraLensIcon(CameraLensDirection direction) {
  19. switch (direction) {
  20. case CameraLensDirection.back:
  21. return Icons.camera_rear;
  22. case CameraLensDirection.front:
  23. return Icons.camera_front;
  24. case CameraLensDirection.external:
  25. return Icons.camera;
  26. }
  27. throw ArgumentError('Unknown lens direction');
  28. }
  29. void logError(String code, String message) =>
  30. print('Error: $code\nError Message: $message');
  31. class _CameraExampleHomeState extends State<CameraExampleHome>
  32. with WidgetsBindingObserver {
  33. CameraController controller;
  34. String imagePath;
  35. String videoPath;
  36. VideoPlayerController videoController;
  37. VoidCallback videoPlayerListener;
  38. bool enableAudio = true;
  39. @override
  40. void initState() {
  41. super.initState();
  42. WidgetsBinding.instance.addObserver(this);
  43. }
  44. @override
  45. void dispose() {
  46. WidgetsBinding.instance.removeObserver(this);
  47. super.dispose();
  48. }
  49. @override
  50. void didChangeAppLifecycleState(AppLifecycleState state) {
  51. // App state changed before we got the chance to initialize.
  52. if (controller == null || !controller.value.isInitialized) {
  53. return;
  54. }
  55. if (state == AppLifecycleState.inactive) {
  56. controller?.dispose();
  57. } else if (state == AppLifecycleState.resumed) {
  58. if (controller != null) {
  59. onNewCameraSelected(controller.description);
  60. }
  61. }
  62. }
  63. final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  64. @override
  65. Widget build(BuildContext context) {
  66. return Scaffold(
  67. key: _scaffoldKey,
  68. appBar: AppBar(
  69. title: const Text('Camera example'),
  70. ),
  71. body: Column(
  72. children: <Widget>[
  73. Expanded(
  74. child: Container(
  75. child: Padding(
  76. padding: const EdgeInsets.all(1.0),
  77. child: Center(
  78. child: _cameraPreviewWidget(),
  79. ),
  80. ),
  81. decoration: BoxDecoration(
  82. color: Colors.black,
  83. border: Border.all(
  84. color: controller != null && controller.value.isRecordingVideo
  85. ? Colors.redAccent
  86. : Colors.grey,
  87. width: 3.0,
  88. ),
  89. ),
  90. ),
  91. ),
  92. _captureControlRowWidget(),
  93. _toggleAudioWidget(),
  94. Padding(
  95. padding: const EdgeInsets.all(5.0),
  96. child: Row(
  97. mainAxisAlignment: MainAxisAlignment.start,
  98. children: <Widget>[
  99. _cameraTogglesRowWidget(),
  100. _thumbnailWidget(),
  101. ],
  102. ),
  103. ),
  104. ],
  105. ),
  106. );
  107. }
  108. /// Display the preview from the camera (or a message if the preview is not available).
  109. Widget _cameraPreviewWidget() {
  110. if (controller == null || !controller.value.isInitialized) {
  111. return const Text(
  112. 'Tap a camera',
  113. style: TextStyle(
  114. color: Colors.white,
  115. fontSize: 24.0,
  116. fontWeight: FontWeight.w900,
  117. ),
  118. );
  119. } else {
  120. return AspectRatio(
  121. aspectRatio: controller.value.aspectRatio,
  122. child: CameraPreview(controller),
  123. );
  124. }
  125. }
  126. /// Toggle recording audio
  127. Widget _toggleAudioWidget() {
  128. return Padding(
  129. padding: const EdgeInsets.only(left: 25),
  130. child: Row(
  131. children: <Widget>[
  132. const Text('Enable Audio:'),
  133. Switch(
  134. value: enableAudio,
  135. onChanged: (bool value) {
  136. enableAudio = value;
  137. if (controller != null) {
  138. onNewCameraSelected(controller.description);
  139. }
  140. },
  141. ),
  142. ],
  143. ),
  144. );
  145. }
  146. /// Display the thumbnail of the captured image or video.
  147. Widget _thumbnailWidget() {
  148. return Expanded(
  149. child: Align(
  150. alignment: Alignment.centerRight,
  151. child: Row(
  152. mainAxisSize: MainAxisSize.min,
  153. children: <Widget>[
  154. videoController == null && imagePath == null
  155. ? Container()
  156. : SizedBox(
  157. child: (videoController == null)
  158. ? Image.file(File(imagePath))
  159. : Container(
  160. child: Center(
  161. child: AspectRatio(
  162. aspectRatio:
  163. videoController.value.size != null
  164. ? videoController.value.aspectRatio
  165. : 1.0,
  166. child: VideoPlayer(videoController)),
  167. ),
  168. decoration: BoxDecoration(
  169. border: Border.all(color: Colors.pink)),
  170. ),
  171. width: 64.0,
  172. height: 64.0,
  173. ),
  174. ],
  175. ),
  176. ),
  177. );
  178. }
  179. /// Display the control bar with buttons to take pictures and record videos.
  180. Widget _captureControlRowWidget() {
  181. return Row(
  182. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  183. mainAxisSize: MainAxisSize.max,
  184. children: <Widget>[
  185. IconButton(
  186. icon: const Icon(Icons.camera_alt),
  187. color: Colors.blue,
  188. onPressed: controller != null &&
  189. controller.value.isInitialized &&
  190. !controller.value.isRecordingVideo
  191. ? onTakePictureButtonPressed
  192. : null,
  193. ),
  194. IconButton(
  195. icon: const Icon(Icons.videocam),
  196. color: Colors.blue,
  197. onPressed: controller != null &&
  198. controller.value.isInitialized &&
  199. !controller.value.isRecordingVideo
  200. ? onVideoRecordButtonPressed
  201. : null,
  202. ),
  203. IconButton(
  204. icon: controller != null && controller.value.isRecordingPaused
  205. ? Icon(Icons.play_arrow)
  206. : Icon(Icons.pause),
  207. color: Colors.blue,
  208. onPressed: controller != null &&
  209. controller.value.isInitialized &&
  210. controller.value.isRecordingVideo
  211. ? (controller != null && controller.value.isRecordingPaused
  212. ? onResumeButtonPressed
  213. : onPauseButtonPressed)
  214. : null,
  215. ),
  216. IconButton(
  217. icon: const Icon(Icons.stop),
  218. color: Colors.red,
  219. onPressed: controller != null &&
  220. controller.value.isInitialized &&
  221. controller.value.isRecordingVideo
  222. ? onStopButtonPressed
  223. : null,
  224. )
  225. ],
  226. );
  227. }
  228. /// Display a row of toggle to select the camera (or a message if no camera is available).
  229. Widget _cameraTogglesRowWidget() {
  230. final List<Widget> toggles = <Widget>[];
  231. if (cameras.isEmpty) {
  232. return const Text('No camera found');
  233. } else {
  234. for (CameraDescription cameraDescription in cameras) {
  235. toggles.add(
  236. SizedBox(
  237. width: 90.0,
  238. child: RadioListTile<CameraDescription>(
  239. title: Icon(getCameraLensIcon(cameraDescription.lensDirection)),
  240. groupValue: controller?.description,
  241. value: cameraDescription,
  242. onChanged: controller != null && controller.value.isRecordingVideo
  243. ? null
  244. : onNewCameraSelected,
  245. ),
  246. ),
  247. );
  248. }
  249. }
  250. return Row(children: toggles);
  251. }
  252. String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();
  253. void showInSnackBar(String message) {
  254. _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(message)));
  255. }
  256. void onNewCameraSelected(CameraDescription cameraDescription) async {
  257. if (controller != null) {
  258. await controller.dispose();
  259. }
  260. controller = CameraController(
  261. cameraDescription,
  262. ResolutionPreset.medium,
  263. enableAudio: enableAudio,
  264. );
  265. // If the controller is updated then update the UI.
  266. controller.addListener(() {
  267. if (mounted) setState(() {});
  268. if (controller.value.hasError) {
  269. showInSnackBar('Camera error ${controller.value.errorDescription}');
  270. }
  271. });
  272. try {
  273. await controller.initialize();
  274. } on CameraException catch (e) {
  275. _showCameraException(e);
  276. }
  277. if (mounted) {
  278. setState(() {});
  279. }
  280. }
  281. void onTakePictureButtonPressed() {
  282. takePicture().then((String filePath) {
  283. if (mounted) {
  284. setState(() {
  285. imagePath = filePath;
  286. videoController?.dispose();
  287. videoController = null;
  288. });
  289. if (filePath != null) showInSnackBar('Picture saved to $filePath');
  290. }
  291. });
  292. }
  293. void onVideoRecordButtonPressed() {
  294. startVideoRecording().then((String filePath) {
  295. if (mounted) setState(() {});
  296. if (filePath != null) showInSnackBar('Saving video to $filePath');
  297. });
  298. }
  299. void onStopButtonPressed() {
  300. stopVideoRecording().then((_) {
  301. if (mounted) setState(() {});
  302. showInSnackBar('Video recorded to: $videoPath');
  303. });
  304. }
  305. void onPauseButtonPressed() {
  306. pauseVideoRecording().then((_) {
  307. if (mounted) setState(() {});
  308. showInSnackBar('Video recording paused');
  309. });
  310. }
  311. void onResumeButtonPressed() {
  312. resumeVideoRecording().then((_) {
  313. if (mounted) setState(() {});
  314. showInSnackBar('Video recording resumed');
  315. });
  316. }
  317. Future<String> startVideoRecording() async {
  318. if (!controller.value.isInitialized) {
  319. showInSnackBar('Error: select a camera first.');
  320. return null;
  321. }
  322. final Directory extDir = await getApplicationDocumentsDirectory();
  323. final String dirPath = '${extDir.path}/Movies/flutter_test';
  324. await Directory(dirPath).create(recursive: true);
  325. final String filePath = '$dirPath/${timestamp()}.mp4';
  326. if (controller.value.isRecordingVideo) {
  327. // A recording is already started, do nothing.
  328. return null;
  329. }
  330. try {
  331. videoPath = filePath;
  332. await controller.startVideoRecording(filePath);
  333. } on CameraException catch (e) {
  334. _showCameraException(e);
  335. return null;
  336. }
  337. return filePath;
  338. }
  339. Future<void> stopVideoRecording() async {
  340. if (!controller.value.isRecordingVideo) {
  341. return null;
  342. }
  343. try {
  344. await controller.stopVideoRecording();
  345. } on CameraException catch (e) {
  346. _showCameraException(e);
  347. return null;
  348. }
  349. await _startVideoPlayer();
  350. }
  351. Future<void> pauseVideoRecording() async {
  352. if (!controller.value.isRecordingVideo) {
  353. return null;
  354. }
  355. try {
  356. await controller.pauseVideoRecording();
  357. } on CameraException catch (e) {
  358. _showCameraException(e);
  359. rethrow;
  360. }
  361. }
  362. Future<void> resumeVideoRecording() async {
  363. if (!controller.value.isRecordingVideo) {
  364. return null;
  365. }
  366. try {
  367. await controller.resumeVideoRecording();
  368. } on CameraException catch (e) {
  369. _showCameraException(e);
  370. rethrow;
  371. }
  372. }
  373. Future<void> _startVideoPlayer() async {
  374. final VideoPlayerController vcontroller =
  375. VideoPlayerController.file(File(videoPath));
  376. videoPlayerListener = () {
  377. if (videoController != null && videoController.value.size != null) {
  378. // Refreshing the state to update video player with the correct ratio.
  379. if (mounted) setState(() {});
  380. videoController.removeListener(videoPlayerListener);
  381. }
  382. };
  383. vcontroller.addListener(videoPlayerListener);
  384. await vcontroller.setLooping(true);
  385. await vcontroller.initialize();
  386. await videoController?.dispose();
  387. if (mounted) {
  388. setState(() {
  389. imagePath = null;
  390. videoController = vcontroller;
  391. });
  392. }
  393. await vcontroller.play();
  394. }
  395. Future<String> takePicture() async {
  396. if (!controller.value.isInitialized) {
  397. showInSnackBar('Error: select a camera first.');
  398. return null;
  399. }
  400. final Directory extDir = await getApplicationDocumentsDirectory();
  401. final String dirPath = '${extDir.path}/Pictures/flutter_test';
  402. await Directory(dirPath).create(recursive: true);
  403. final String filePath = '$dirPath/${timestamp()}.jpg';
  404. if (controller.value.isTakingPicture) {
  405. // A capture is already pending, do nothing.
  406. return null;
  407. }
  408. try {
  409. await controller.takePicture(filePath);
  410. } on CameraException catch (e) {
  411. _showCameraException(e);
  412. return null;
  413. }
  414. return filePath;
  415. }
  416. void _showCameraException(CameraException e) {
  417. logError(e.code, e.description);
  418. showInSnackBar('Error: ${e.code}\n${e.description}');
  419. }
  420. }
  421. class CameraApp extends StatelessWidget {
  422. @override
  423. Widget build(BuildContext context) {
  424. return MaterialApp(
  425. home: CameraExampleHome(),
  426. );
  427. }
  428. }
  429. List<CameraDescription> cameras = [];
  430. Future<void> main() async {
  431. // Fetch the available cameras before initializing the app.
  432. try {
  433. WidgetsFlutterBinding.ensureInitialized();
  434. cameras = await availableCameras();
  435. } on CameraException catch (e) {
  436. logError(e.code, e.description);
  437. }
  438. runApp(CameraApp());
  439. }

如果代码运行遇到困难,请直接查看camera官方文档

PlatformView (示例:WebView)

如果我们在开发过程中需要使用一个原生组件,但这个原生组件在Flutter中很难实现时怎么办(如webview)?这时一个简单的方法就是将需要使用原生组件的页面全部用原生实现,在flutter中需要打开该页面时通过消息通道打开这个原生的页面。但是这种方法有一个最大的缺点,就是原生组件很难和Flutter组件进行组合。
在 Flutter 1.0版本中,Flutter SDK中新增了AndroidView和UIKitView 两个组件,这两个组件的主要功能就是将原生的Android组件和iOS组件嵌入到Flutter的组件树中,这个功能是非常重要的,尤其是对一些实现非常复杂的组件,比如webview,这些组件原生已经有了,如果Flutter中要用,重新实现的话成本将非常高,所以如果有一种机制能让Flutter共享原生组件,这将会非常有用,也正因如此,Flutter才提供了这两个组件。
由于AndroidView和UIKitView 是和具体平台相关的,所以称它们为PlatformView。需要说明的是将来Flutter支持的平台可能会增多,则相应的PlatformView也将会变多。那么如何使用Platform View呢?我们以Flutter官方提供的webview_flutter插件为例:

注意,在本书写作之时,webview_flutter仍处于预览阶段,如您想在项目中使用它,请查看一下webview_flutter插件最新版本及动态。

原生代码中注册要被Flutter嵌入的组件工厂,如webview_flutter插件中Android端注册webview插件代码:

  1. public static void registerWith(Registrar registrar) {
  2. registrar.platformViewRegistry().registerViewFactory("webview",
  3. WebViewFactory(registrar.messenger()));
  4. }

WebViewFactory的具体实现请参考 webview_flutter 插件的实现源码,在此不再赘述

  1. 首先需要添加依赖到pubspec.yaml文件中

    1. dependencies:
    2. webview_flutter: ^0.3.21
  2. 在Flutter中使用;打开Flutter中文社区首页。 ```dart // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import ‘dart:async’; import ‘dart:convert’; import ‘package:flutter/material.dart’; import ‘package:webview_flutter/webview_flutter.dart’;

void main() => runApp(MaterialApp(home: WebViewExample()));

const String kNavigationExamplePage = ‘’’ <!DOCTYPE html>

The navigation delegate is set to block navigation to the youtube website.

‘’’;

class WebViewExample extends StatefulWidget { @override _WebViewExampleState createState() => _WebViewExampleState(); }

class _WebViewExampleState extends State { final Completer _controller = Completer();

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(‘Flutter WebView example’), // This drop down menu demonstrates that Flutter widgets can be shown over the web view. actions: [ NavigationControls(_controller.future), SampleMenu(_controller.future), ], ), // We’re using a Builder here so we have a context that is below the Scaffold // to allow calling Scaffold.of(context) so we can show a snackbar. body: Builder(builder: (BuildContext context) { return WebView( initialUrl: ‘https://flutter.cn‘, javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController webViewController) { _controller.complete(webViewController); }, // TODO(iskakaushik): Remove this when collection literals makes it to stable. // ignore: prefer_collection_literals javascriptChannels: [ _toasterJavascriptChannel(context), ].toSet(), navigationDelegate: (NavigationRequest request) { if (request.url.startsWith(‘https://www.youtube.com/‘)) { print(‘blocking navigation to $request}’); return NavigationDecision.prevent; } print(‘allowing navigation to $request’); return NavigationDecision.navigate; }, onPageStarted: (String url) { print(‘Page started loading: $url’); }, onPageFinished: (String url) { print(‘Page finished loading: $url’); }, gestureNavigationEnabled: true, ); }), floatingActionButton: favoriteButton(), ); }

JavascriptChannel _toasterJavascriptChannel(BuildContext context) { return JavascriptChannel( name: ‘Toaster’, onMessageReceived: (JavascriptMessage message) { Scaffold.of(context).showSnackBar( SnackBar(content: Text(message.message)), ); }); }

Widget favoriteButton() { return FutureBuilder( future: _controller.future, builder: (BuildContext context, AsyncSnapshot controller) { if (controller.hasData) { return FloatingActionButton( onPressed: () async { final String url = await controller.data.currentUrl(); Scaffold.of(context).showSnackBar( SnackBar(content: Text(‘Favorited $url’)), ); }, child: const Icon(Icons.favorite), ); } return Container(); }); } }

enum MenuOptions { showUserAgent, listCookies, clearCookies, addToCache, listCache, clearCache, navigationDelegate, }

class SampleMenu extends StatelessWidget { SampleMenu(this.controller);

final Future controller; final CookieManager cookieManager = CookieManager();

void _onShowUserAgent( WebViewController controller, BuildContext context) async { // Send a message with the user agent string to the Toaster JavaScript channel we registered // with the WebView. await controller.evaluateJavascript( ‘Toaster.postMessage(“User Agent: “ + navigator.userAgent);’); }

void _onListCookies( WebViewController controller, BuildContext context) async { final String cookies = await controller.evaluateJavascript(‘document.cookie’); Scaffold.of(context).showSnackBar(SnackBar( content: Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ const Text(‘Cookies:’), _getCookieList(cookies), ], ), )); }

void _onAddToCache(WebViewController controller, BuildContext context) async { await controller.evaluateJavascript( ‘caches.open(“test_caches_entry”); localStorage[“test_localStorage”] = “dummy_entry”;’); Scaffold.of(context).showSnackBar(const SnackBar( content: Text(‘Added a test entry to cache.’), )); }

void _onListCache(WebViewController controller, BuildContext context) async { await controller.evaluateJavascript(‘caches.keys()’ ‘.then((cacheKeys) => JSON.stringify({“cacheKeys” : cacheKeys, “localStorage” : localStorage}))’ ‘.then((caches) => Toaster.postMessage(caches))’); }

void _onClearCache(WebViewController controller, BuildContext context) async { await controller.clearCache(); Scaffold.of(context).showSnackBar(const SnackBar( content: Text(“Cache cleared.”), )); }

void _onClearCookies(BuildContext context) async { final bool hadCookies = await cookieManager.clearCookies(); String message = ‘There were cookies. Now, they are gone!’; if (!hadCookies) { message = ‘There are no cookies.’; } Scaffold.of(context).showSnackBar(SnackBar( content: Text(message), )); }

void _onNavigationDelegateExample( WebViewController controller, BuildContext context) async { final String contentBase64 = base64Encode(const Utf8Encoder().convert(kNavigationExamplePage)); await controller.loadUrl(‘data:text/html;base64,$contentBase64’); }

Widget _getCookieList(String cookies) { if (cookies == null || cookies == ‘“”‘) { return Container(); } final List cookieList = cookies.split(‘;’); final Iterable cookieWidgets = cookieList.map((String cookie) => Text(cookie)); return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: cookieWidgets.toList(), ); }

@override Widget build(BuildContext context) { return FutureBuilder( future: controller, builder: (BuildContext context, AsyncSnapshot controller) { return PopupMenuButton( onSelected: (MenuOptions value) { switch (value) { case MenuOptions.showUserAgent: _onShowUserAgent(controller.data, context); break; case MenuOptions.listCookies: _onListCookies(controller.data, context); break; case MenuOptions.clearCookies: _onClearCookies(context); break; case MenuOptions.addToCache: _onAddToCache(controller.data, context); break; case MenuOptions.listCache: _onListCache(controller.data, context); break; case MenuOptions.clearCache: _onClearCache(controller.data, context); break; case MenuOptions.navigationDelegate: _onNavigationDelegateExample(controller.data, context); break; } }, itemBuilder: (BuildContext context) => >[ PopupMenuItem( value: MenuOptions.showUserAgent, child: const Text(‘Show user agent’), enabled: controller.hasData, ), const PopupMenuItem( value: MenuOptions.listCookies, child: Text(‘List cookies’), ), const PopupMenuItem( value: MenuOptions.clearCookies, child: Text(‘Clear cookies’), ), const PopupMenuItem( value: MenuOptions.addToCache, child: Text(‘Add to cache’), ), const PopupMenuItem( value: MenuOptions.listCache, child: Text(‘List cache’), ), const PopupMenuItem( value: MenuOptions.clearCache, child: Text(‘Clear cache’), ), const PopupMenuItem( value: MenuOptions.navigationDelegate, child: Text(‘Navigation Delegate example’), ), ], ); }, ); } }

class NavigationControls extends StatelessWidget { const NavigationControls(this._webViewControllerFuture) : assert(_webViewControllerFuture != null);

final Future _webViewControllerFuture;

@override Widget build(BuildContext context) { return FutureBuilder( future: _webViewControllerFuture, builder: (BuildContext context, AsyncSnapshot snapshot) { final bool webViewReady = snapshot.connectionState == ConnectionState.done; final WebViewController controller = snapshot.data; return Row( children: [ IconButton( icon: const Icon(Icons.arrow_back_ios), onPressed: !webViewReady ? null : () async { if (await controller.canGoBack()) { await controller.goBack(); } else { Scaffold.of(context).showSnackBar( const SnackBar(content: Text(“No back history item”)), ); return; } }, ), IconButton( icon: const Icon(Icons.arrow_forward_ios), onPressed: !webViewReady ? null : () async { if (await controller.canGoForward()) { await controller.goForward(); } else { Scaffold.of(context).showSnackBar( const SnackBar( content: Text(“No forward history item”)), ); return; } }, ), IconButton( icon: const Icon(Icons.replay), onPressed: !webViewReady ? null : () { controller.reload(); }, ), ], ); }, ); } } ``` 运行效果如图
Texture和PlatformView - 图2
注意,使用PlatformView的开销是非常大的,因此,如果一个原生组件用Flutter实现的难度不大时,我们应该首选Flutter实现。
另外,PlatformView的相关功能在作者写作时还处于预览阶段,可能还会发生变化,因此,读者如果需要在项目中使用的话,应查看一下最新的文档。