我曾尝试将Flutter camera plugin(0.2.1)与PageView和BottomNavigationBar结合使用,但每次切换页面时,都会跳过几帧,UI会冻结一秒钟 .
我为这个例子简化了我的代码库:
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
void main() => runApp(new Pages());
class Pages extends StatefulWidget {
@override
_PagesState createState() => _PagesState();
}
class _PagesState extends State<Pages> {
PageController _pageController;
int _page = 0;
@override
void initState() {
_pageController = new PageController();
super.initState();
}
void navTapped(int page) {
_pageController.animateToPage(page,
duration: const Duration(milliseconds: 300), curve: Curves.ease);
}
void onPageChanged(int page) {
setState(() {
this._page = page;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: new Text("CameraTest"),
),
body: PageView(
children: <Widget>[Feed(), Camera(), Profile()],
controller: _pageController,
onPageChanged: onPageChanged,
),
bottomNavigationBar: new BottomNavigationBar(
items: [
new BottomNavigationBarItem(
icon: new Icon(Icons.home), title: new Text("Feed")),
new BottomNavigationBarItem(
icon: new Icon(Icons.camera), title: new Text("Capture")),
new BottomNavigationBarItem(
icon: new Icon(Icons.person), title: new Text("Profile"))
],
onTap: navTapped,
currentIndex: _page,
),
),
);
}
}
class Camera extends StatefulWidget {
@override
_CameraState createState() => _CameraState();
}
class _CameraState extends State<Camera> {
List<CameraDescription> _cameras;
CameraController _controller;
initCameras() async{
_cameras = await availableCameras();
_controller = new CameraController(_cameras[0], ResolutionPreset.medium);
await _controller.initialize();
setState(() {});
}
@override
void initState() {
initCameras();
super.initState();
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_controller == null || !_controller.value.isInitialized) {
return new Center(
child: new Text("Waiting for camera...", style: TextStyle(color: Colors.grey),),
);
}
return new AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: new CameraPreview(_controller));
}
}
//just placeholder widgets
class Feed extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: new Text("Feed"));
}
}
class Profile extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: new Text("Profile"));
}
}
基本上有三个页面,中间的一个显示相机预览(how it's supposed to look),但在切换到相机并从它返回时this发生 . 这真的很烦人,因为它破坏了用户体验并且根本不光滑 . 调用initCameras()或处理摄像机控制器时出现滞后 . 我尝试将initCameras()与FutureBuilder结合使用,后者不需要太多的CPU功率,因此异步方法应该没问题 . 我知道有一个image-picker plugin,但我希望直接在应用程序中进行预览 . 我还考虑过在app start上运行initCameras(),但是当用户只是使用应用程序的另一个页面时,我不想让相机一直运行 .
有没有办法改进initCameras()或者使用不同的实现来修复口吃?我甚至不在乎是否需要一秒钟加载,但我不希望任何帧跳过 .
我跟着相机页面底部的example .
在不同的Android版本上测试物理设备和模拟器 .
1 回答
如果要在不同的页面中使用图像路径而不是将图像路径存储为全局变量,请在需要的位置使用它 .