Flutter實戰(zhàn) Textrue和PlatformView

2021-03-09 14:02 更新

本節(jié)主要介紹原生和 Flutter 之間如何共享圖像,以及如何在 Flutter 中嵌套原生組件。

#12.6.1 Texture(示例:使用攝像頭)

前面說過 Flutter 本身只是一個UI系統(tǒng),對于一些系統(tǒng)能力的調(diào)用我們可以通過消息傳送機制與原生交互。但是這種消息傳送機制并不能覆蓋所有的應(yīng)用場景,比如我們想調(diào)用攝像頭來拍照或錄視頻,但在拍照和錄視頻的過程中我們需要將預(yù)覽畫面顯示到我們的 Flutter UI 中,如果我們要用 Flutter 定義的消息通道機制來實現(xiàn)這個功能,就需要將攝像頭采集的每一幀圖片都要從原生傳遞到 Flutter 中,這樣做代價將會非常大,因為將圖像或視頻數(shù)據(jù)通過消息通道實時傳輸必然會引起內(nèi)存和 CPU 的巨大消耗!為此,F(xiàn)lutter 提供了一種基于 Texture 的圖片數(shù)據(jù)共享機制。

Texture 可以理解為 GPU 內(nèi)保存將要繪制的圖像數(shù)據(jù)的一個對象,F(xiàn)lutter engine 會將 Texture 的數(shù)據(jù)在內(nèi)存中直接進行映射(而無需在原生和 Flutter 之間再進行數(shù)據(jù)傳遞),F(xiàn)lutter 會給每一個 Texture 分配一個 id,同時 Flutter 中提供了一個Texture組件,Texture構(gòu)造函數(shù)定義如下:

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

Texture 組件正是通過textureId與 Texture 數(shù)據(jù)關(guān)聯(lián)起來;在Texture組件繪制時,F(xiàn)lutter 會自動從內(nèi)存中找到相應(yīng) id 的 Texture 數(shù)據(jù),然后進行繪制??梢钥偨Y(jié)一下整個流程:圖像數(shù)據(jù)先在原生部分緩存,然后在 Flutter 部分再通過textureId和緩存關(guān)聯(lián)起來,最后繪制由 Flutter 完成。

如果我們作為一個插件開發(fā)者,我們在原生代碼中分配了textureId,那么在 Flutter 側(cè)使用Texture組件時要如何獲取textureId呢?這又回到了之前的內(nèi)容了,textureId完全可以通過 MethodChannel 來傳遞。

另外,值得注意的是,當原生攝像頭捕獲的圖像發(fā)生變化時,Texture 組件會自動重繪,這不需要我們寫任何 Dart 代碼去控制。

#Texture用法

如果我們要手動實現(xiàn)一個相機插件,和前面幾節(jié)介紹的“獲取剩余電量”插件的步驟一樣,需要分別實現(xiàn)原生部分和 Flutter 部分??紤]到大多數(shù)讀者可能并非同時既了解 Android 開發(fā),又了解 iOS 開發(fā),如果我們再花大量篇幅來介紹不同端的實現(xiàn)可能會沒什么意義,另外,由于 Flutter 官方提供的相機(camera)插件和視頻播放(video_player)插件都是使用 Texture 來實現(xiàn)的,它們本身就是 Texture 非常好的示例,所以在本書中將不會再介紹使用 Texture 的具體流程了,讀者有興趣查看 camera和video_player 的實現(xiàn)代碼。下面我們重點介紹一下如何使用 camera 和 video_player。

#相機示例

下面我們看一下 camera 包自帶的一個示例,它包含如下功能:

  1. 可以拍照,也可以拍視頻,拍攝完成后可以保存;排號的視頻可以播放預(yù)覽。
  2. 可以切換攝像頭(前置攝像頭、后置攝像頭、其它)
  3. 可以顯示已經(jīng)拍攝內(nèi)容的預(yù)覽圖。

下面我們看一下具體代碼:

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

  1. dependencies:
  2. ... //省略無關(guān)代碼
  3. camera: ^0.5.2+2

  1. main方法中獲取可用攝像頭列表。

  1. void main() async {
  2. // 獲取可用攝像頭列表,cameras為全局變量
  3. cameras = await availableCameras();
  4. runApp(MyApp());
  5. }

  1. 構(gòu)建UI?,F(xiàn)在我們構(gòu)建如圖12-4的測試界面:

12-4 線面是完整的代碼:

  1. import 'package:camera/camera.dart';
  2. import 'package:flutter/material.dart';
  3. import '../common.dart';
  4. import 'dart:async';
  5. import 'dart:io';
  6. import 'package:path_provider/path_provider.dart';
  7. import 'package:video_player/video_player.dart'; //用于播放錄制的視頻
  8. /// 獲取不同攝像頭的圖標(前置、后置、其它)
  9. IconData getCameraLensIcon(CameraLensDirection direction) {
  10. switch (direction) {
  11. case CameraLensDirection.back:
  12. return Icons.camera_rear;
  13. case CameraLensDirection.front:
  14. return Icons.camera_front;
  15. case CameraLensDirection.external:
  16. return Icons.camera;
  17. }
  18. throw ArgumentError('Unknown lens direction');
  19. }
  20. void logError(String code, String message) =>
  21. print('Error: $code\nError Message: $message');
  22. // 示例頁面路由
  23. class CameraExampleHome extends StatefulWidget {
  24. @override
  25. _CameraExampleHomeState createState() {
  26. return _CameraExampleHomeState();
  27. }
  28. }
  29. class _CameraExampleHomeState extends State<CameraExampleHome>
  30. with WidgetsBindingObserver {
  31. CameraController controller;
  32. String imagePath; // 圖片保存路徑
  33. String videoPath; //視頻保存路徑
  34. VideoPlayerController videoController;
  35. VoidCallback videoPlayerListener;
  36. bool enableAudio = true;
  37. @override
  38. void initState() {
  39. super.initState();
  40. // 監(jiān)聽APP狀態(tài)改變,是否在前臺
  41. WidgetsBinding.instance.addObserver(this);
  42. }
  43. @override
  44. void dispose() {
  45. WidgetsBinding.instance.removeObserver(this);
  46. super.dispose();
  47. }
  48. @override
  49. void didChangeAppLifecycleState(AppLifecycleState state) {
  50. // 如果APP不在在前臺
  51. if (state == AppLifecycleState.inactive) {
  52. controller?.dispose();
  53. } else if (state == AppLifecycleState.resumed) {
  54. // 在前臺
  55. if (controller != null) {
  56. onNewCameraSelected(controller.description);
  57. }
  58. }
  59. }
  60. final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  61. @override
  62. Widget build(BuildContext context) {
  63. return Scaffold(
  64. key: _scaffoldKey,
  65. appBar: AppBar(
  66. title: const Text('相機示例'),
  67. ),
  68. body: Column(
  69. children: <Widget>[
  70. Expanded(
  71. child: Container(
  72. child: Padding(
  73. padding: const EdgeInsets.all(1.0),
  74. child: Center(
  75. child: _cameraPreviewWidget(),
  76. ),
  77. ),
  78. decoration: BoxDecoration(
  79. color: Colors.black,
  80. border: Border.all(
  81. color: controller != null && controller.value.isRecordingVideo
  82. ? Colors.redAccent
  83. : Colors.grey,
  84. width: 3.0,
  85. ),
  86. ),
  87. ),
  88. ),
  89. _captureControlRowWidget(),
  90. _toggleAudioWidget(),
  91. Padding(
  92. padding: const EdgeInsets.all(5.0),
  93. child: Row(
  94. mainAxisAlignment: MainAxisAlignment.start,
  95. children: <Widget>[
  96. _cameraTogglesRowWidget(),
  97. _thumbnailWidget(),
  98. ],
  99. ),
  100. ),
  101. ],
  102. ),
  103. );
  104. }
  105. /// 展示預(yù)覽窗口
  106. Widget _cameraPreviewWidget() {
  107. if (controller == null || !controller.value.isInitialized) {
  108. return const Text(
  109. '選擇一個攝像頭',
  110. style: TextStyle(
  111. color: Colors.white,
  112. fontSize: 24.0,
  113. fontWeight: FontWeight.w900,
  114. ),
  115. );
  116. } else {
  117. return AspectRatio(
  118. aspectRatio: controller.value.aspectRatio,
  119. child: CameraPreview(controller),
  120. );
  121. }
  122. }
  123. /// 開啟或關(guān)閉錄音
  124. Widget _toggleAudioWidget() {
  125. return Padding(
  126. padding: const EdgeInsets.only(left: 25),
  127. child: Row(
  128. children: <Widget>[
  129. const Text('開啟錄音:'),
  130. Switch(
  131. value: enableAudio,
  132. onChanged: (bool value) {
  133. enableAudio = value;
  134. if (controller != null) {
  135. onNewCameraSelected(controller.description);
  136. }
  137. },
  138. ),
  139. ],
  140. ),
  141. );
  142. }
  143. /// 顯示已拍攝的圖片/視頻縮略圖。
  144. Widget _thumbnailWidget() {
  145. return Expanded(
  146. child: Align(
  147. alignment: Alignment.centerRight,
  148. child: Row(
  149. mainAxisSize: MainAxisSize.min,
  150. children: <Widget>[
  151. videoController == null && imagePath == null
  152. ? Container()
  153. : SizedBox(
  154. child: (videoController == null)
  155. ? Image.file(File(imagePath))
  156. : Container(
  157. child: Center(
  158. child: AspectRatio(
  159. aspectRatio:
  160. videoController.value.size != null
  161. ? videoController.value.aspectRatio
  162. : 1.0,
  163. child: VideoPlayer(videoController)),
  164. ),
  165. decoration: BoxDecoration(
  166. border: Border.all(color: Colors.pink)),
  167. ),
  168. width: 64.0,
  169. height: 64.0,
  170. ),
  171. ],
  172. ),
  173. ),
  174. );
  175. }
  176. /// 相機工具欄
  177. Widget _captureControlRowWidget() {
  178. return Row(
  179. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  180. mainAxisSize: MainAxisSize.max,
  181. children: <Widget>[
  182. IconButton(
  183. icon: const Icon(Icons.camera_alt),
  184. color: Colors.blue,
  185. onPressed: controller != null &&
  186. controller.value.isInitialized &&
  187. !controller.value.isRecordingVideo
  188. ? onTakePictureButtonPressed
  189. : null,
  190. ),
  191. IconButton(
  192. icon: const Icon(Icons.videocam),
  193. color: Colors.blue,
  194. onPressed: controller != null &&
  195. controller.value.isInitialized &&
  196. !controller.value.isRecordingVideo
  197. ? onVideoRecordButtonPressed
  198. : null,
  199. ),
  200. IconButton(
  201. icon: const Icon(Icons.stop),
  202. color: Colors.red,
  203. onPressed: controller != null &&
  204. controller.value.isInitialized &&
  205. controller.value.isRecordingVideo
  206. ? onStopButtonPressed
  207. : null,
  208. )
  209. ],
  210. );
  211. }
  212. /// 展示所有攝像頭
  213. Widget _cameraTogglesRowWidget() {
  214. final List<Widget> toggles = <Widget>[];
  215. if (cameras.isEmpty) {
  216. return const Text('沒有檢測到攝像頭');
  217. } else {
  218. for (CameraDescription cameraDescription in cameras) {
  219. toggles.add(
  220. SizedBox(
  221. width: 90.0,
  222. child: RadioListTile<CameraDescription>(
  223. title: Icon(getCameraLensIcon(cameraDescription.lensDirection)),
  224. groupValue: controller?.description,
  225. value: cameraDescription,
  226. onChanged: controller != null && controller.value.isRecordingVideo
  227. ? null
  228. : onNewCameraSelected,
  229. ),
  230. ),
  231. );
  232. }
  233. }
  234. return Row(children: toggles);
  235. }
  236. String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();
  237. void showInSnackBar(String message) {
  238. _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(message)));
  239. }
  240. // 攝像頭選中回調(diào)
  241. void onNewCameraSelected(CameraDescription cameraDescription) async {
  242. if (controller != null) {
  243. await controller.dispose();
  244. }
  245. controller = CameraController(
  246. cameraDescription,
  247. ResolutionPreset.high,
  248. enableAudio: enableAudio,
  249. );
  250. controller.addListener(() {
  251. if (mounted) setState(() {});
  252. if (controller.value.hasError) {
  253. showInSnackBar('Camera error ${controller.value.errorDescription}');
  254. }
  255. });
  256. try {
  257. await controller.initialize();
  258. } on CameraException catch (e) {
  259. _showCameraException(e);
  260. }
  261. if (mounted) {
  262. setState(() {});
  263. }
  264. }
  265. // 拍照按鈕點擊回調(diào)
  266. void onTakePictureButtonPressed() {
  267. takePicture().then((String filePath) {
  268. if (mounted) {
  269. setState(() {
  270. imagePath = filePath;
  271. videoController?.dispose();
  272. videoController = null;
  273. });
  274. if (filePath != null) showInSnackBar('圖片保存在 $filePath');
  275. }
  276. });
  277. }
  278. // 開始錄制視頻
  279. void onVideoRecordButtonPressed() {
  280. startVideoRecording().then((String filePath) {
  281. if (mounted) setState(() {});
  282. if (filePath != null) showInSnackBar('正在保存視頻于 $filePath');
  283. });
  284. }
  285. // 終止視頻錄制
  286. void onStopButtonPressed() {
  287. stopVideoRecording().then((_) {
  288. if (mounted) setState(() {});
  289. showInSnackBar('視頻保存在: $videoPath');
  290. });
  291. }
  292. Future<String> startVideoRecording() async {
  293. if (!controller.value.isInitialized) {
  294. showInSnackBar('請先選擇一個攝像頭');
  295. return null;
  296. }
  297. // 確定視頻保存的路徑
  298. final Directory extDir = await getApplicationDocumentsDirectory();
  299. final String dirPath = '${extDir.path}/Movies/flutter_test';
  300. await Directory(dirPath).create(recursive: true);
  301. final String filePath = '$dirPath/${timestamp()}.mp4';
  302. if (controller.value.isRecordingVideo) {
  303. // 如果正在錄制,則直接返回
  304. return null;
  305. }
  306. try {
  307. videoPath = filePath;
  308. await controller.startVideoRecording(filePath);
  309. } on CameraException catch (e) {
  310. _showCameraException(e);
  311. return null;
  312. }
  313. return filePath;
  314. }
  315. Future<void> stopVideoRecording() async {
  316. if (!controller.value.isRecordingVideo) {
  317. return null;
  318. }
  319. try {
  320. await controller.stopVideoRecording();
  321. } on CameraException catch (e) {
  322. _showCameraException(e);
  323. return null;
  324. }
  325. await _startVideoPlayer();
  326. }
  327. Future<void> _startVideoPlayer() async {
  328. final VideoPlayerController vcontroller =
  329. VideoPlayerController.file(File(videoPath));
  330. videoPlayerListener = () {
  331. if (videoController != null && videoController.value.size != null) {
  332. // Refreshing the state to update video player with the correct ratio.
  333. if (mounted) setState(() {});
  334. videoController.removeListener(videoPlayerListener);
  335. }
  336. };
  337. vcontroller.addListener(videoPlayerListener);
  338. await vcontroller.setLooping(true);
  339. await vcontroller.initialize();
  340. await videoController?.dispose();
  341. if (mounted) {
  342. setState(() {
  343. imagePath = null;
  344. videoController = vcontroller;
  345. });
  346. }
  347. await vcontroller.play();
  348. }
  349. Future<String> takePicture() async {
  350. if (!controller.value.isInitialized) {
  351. showInSnackBar('錯誤: 請先選擇一個相機');
  352. return null;
  353. }
  354. final Directory extDir = await getApplicationDocumentsDirectory();
  355. final String dirPath = '${extDir.path}/Pictures/flutter_test';
  356. await Directory(dirPath).create(recursive: true);
  357. final String filePath = '$dirPath/${timestamp()}.jpg';
  358. if (controller.value.isTakingPicture) {
  359. // A capture is already pending, do nothing.
  360. return null;
  361. }
  362. try {
  363. await controller.takePicture(filePath);
  364. } on CameraException catch (e) {
  365. _showCameraException(e);
  366. return null;
  367. }
  368. return filePath;
  369. }
  370. void _showCameraException(CameraException e) {
  371. logError(e.code, e.description);
  372. showInSnackBar('Error: ${e.code}\n${e.description}');
  373. }
  374. }

如果代碼運行遇到困難,請直接查看camera官方文檔 (opens new window)。

#12.6.2 PlatformView (示例:WebView)

如果我們在開發(fā)過程中需要使用一個原生組件,但這個原生組件在 Flutter 中很難實現(xiàn)時怎么辦(如 webview)?這時一個簡單的方法就是將需要使用原生組件的頁面全部用原生實現(xiàn),在 flutter 中需要打開該頁面時通過消息通道打開這個原生的頁面。但是這種方法有一個最大的缺點,就是原生組件很難和 Flutter 組件進行組合。

在 Flutter 1.0版本中,F(xiàn)lutter SDK 中新增了AndroidViewUIKitView 兩個組件,這兩個組件的主要功能就是將原生的 Android 組件和 iOS 組件嵌入到 Flutter 的組件樹中,這個功能是非常重要的,尤其是對一些實現(xiàn)非常復(fù)雜的組件,比如 webview,這些組件原生已經(jīng)有了,如果 Flutter 中要用,重新實現(xiàn)的話成本將非常高,所以如果有一種機制能讓 Flutter 共享原生組件,這將會非常有用,也正因如此,F(xiàn)lutter 才提供了這兩個組件。

由于AndroidViewUIKitView 是和具體平臺相關(guān)的,所以稱它們?yōu)?PlatformView。需要說明的是將來 Flutter 支持的平臺可能會增多,則相應(yīng)的 PlatformView 也將會變多。那么如何使用 Platform View 呢?我們以 Flutter 官方提供的webview_flutter插件 (opens new window)為例:

注意,在本書寫作之時,webview_flutter 仍處于預(yù)覽階段,如您想在項目中使用它,請查看一下 webview_flutter 插件最新版本及動態(tài)。

  1. 原生代碼中注冊要被 Flutter 嵌入的組件工廠,如 webview_flutter 插件中 Android 端注冊webview 插件代碼:

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

WebViewFactory的具體實現(xiàn)請參考 webview_flutter 插件的實現(xiàn)源碼,在此不再贅述。

  1. 在 Flutter 中使用;打開 Flutter 中文社區(qū)首頁。

  1. class PlatformViewRoute extends StatelessWidget {
  2. @override
  3. Widget build(BuildContext context) {
  4. return WebView(
  5. initialUrl: "https://flutterchina.club",
  6. javascriptMode: JavascriptMode.unrestricted,
  7. );
  8. }
  9. }

運行效果如圖12-5所示:

注意,使用 PlatformView 的開銷是非常大的,因此,如果一個原生組件用 Flutter 實現(xiàn)的難度不大時,我們應(yīng)該首選 Flutter 實現(xiàn)。

另外,PlatformView 的相關(guān)功能在作者寫作時還處于預(yù)覽階段,可能還會發(fā)生變化,因此,讀者如果需要在項目中使用的話,應(yīng)查看一下最新的文檔。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號