在图像流中使用websocket时,Flutter相机应用程序的渲染速度非常慢。如何提高应用程序性能?克服此问题的最佳方法是什么?在模拟器上,它工作得很好,但在实际设备上,存在很多延迟和卡顿现象。我们可以在相机应用中使用异步吗?如果是,该如何在代码中使用它?
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:web_socket_channel/io.dart';
import 'dart:convert';
import 'package:archive/archive.dart';
List<CameraDescription> cameras;
Future<void> main() async {
cameras = await availableCameras();
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Title',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: CameraApp(),
);
}
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
IOWebSocketChannel channel = IOWebSocketChannel.connect('ws://192.168.0.6:8000/');
@override
void initState() {
super.initState();
controller = CameraController(cameras[1], ResolutionPreset.low);
controller.initialize().then((_) async{
await controller.startImageStream((onAvailable) {
sd(onAvailable);
});
if (!mounted) {
return;
}
setState(() {});
});
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
void sd(onAvailable) {
var framesY = onAvailable.planes[0].bytes;
List<int> gzipBytes = new GZipEncoder().encode(framesY);
String compressedString = base64Encode(gzipBytes);
channel.sink.add(compressedString);
}
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container();
}
return new Scaffold(
body: new Container(
child: new AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: new CameraPreview(controller),
),
),
);
}
}