【问题标题】:Disposing Camera preview in CupertinoTabBar when switched in Flutter在 Flutter 中切换时在 CupertinoTabBar 中处理相机预览
【发布时间】:2021-11-03 10:52:59
【问题描述】:
我正在构建一个 QR 码扫描仪应用程序,其中有几个选项卡包含在 CupertinoTabScaffold 中的 CupertinoTabBar 中。我有一个 CupertinoTabController 来处理选项卡之间的切换。其中一个选项卡具有来自 Flutter 的 Camera 插件的 CameraPreview 小部件以及适当的处置机制。但是,每当切换选项卡时,相机流仍然存在,导致手机发热并导致 janky UX。现在我读到 Material 小部件中的 BottomNavigationBar 不会以这种方式持续存在。关于如何使用 CupertinoTabBar 实现相同行为的任何想法?
【问题讨论】:
标签:
flutter
android-camera2
flutter-cupertino
cupertinotabbar
【解决方案1】:
您可以为每个页面的选项卡使用StatefulWidget,然后尝试监听AppLifecycleState。如果状态为非活动/暂停,则处理控制器。
就我而言,它工作正常。
class Example extends StatefulWidget {
@override
ExampleState createState() => ExampleState();
}
//Implement WidgetsBindingObserver to listen Lifecycle State
class ExampleState extends State<Example> with WidgetsBindingObserver {
late CameraController _controller;
...
...
@override
void initState() {
super.initState();
// Add Listener (Lifecycle State)
WidgetsBinding.instance!.addObserver(this);
}
Future<void> _setupController() async {
//todo setup/init controller
}
//Implements this method to listen Lifecycle State
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_controller.dispose();
_setupCameraAndControllerFuture = _setupController();
}
if (state == AppLifecycleState.inactive) {
_controller.dispose();
} else if (state == AppLifecycleState.paused) {
_controller.dispose();
}
}
@override
void dispose() {
// Remove Listener (Lifecycle State)
WidgetsBinding.instance!.removeObserver(this);
// dispose controller
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
...
...
);
}
}