Flutter调用异步摄像头小部件

问题描述 投票:0回答:1

我正在使用Flutter应用,正在使用相机。我最初将我的应用程序编码为让main()是访问摄像头的异步函数,但我不再想要这样做,而只是希望小部件是异步的。我的问题是,我该在哪里做?是否使路由异步?还是让我的相机小部件异步?如果有人可以帮助我,我将不胜感激!澄清的评论如下。


import 'package:camera/camera.dart';
import 'dart:async';

import 'package:flutter/material.dart';

import 'CameraScreen.dart';
import 'PictureScreen.dart';



List<CameraDescription> cameras;

//this is where it is currently asynchronous to access the camera.  My question is, where do I move the async code?  There are two options I am considering, but if you have any other ideas please let me know.  

Future<Null> main() async {
WidgetsFlutterBinding.ensureInitialized();
  try {
  cameras = await availableCameras();
} on CameraException catch (e) {
  //logError(e.code, e.description);
}


runApp(
  MaterialApp(
    title: "Matts App",
    debugShowCheckedModeBanner: false,
    initialRoute: 'CameraScreen',
  //home: CameraScreen(cameras),
    routes: {
      'CameraScreen': (BuildContext context) => CameraScreen(cameras),  //I could make it asynchronous right here
      'PICTURE_SCREEN': (BuildContext context) => PictureScreen(),
    },

  ),
);
}

////////////////////

//CameraScreen

//or I could make it asynchronous right here.  

class CameraScreen extends StatefulWidget {
  List<CameraDescription> cameras;

CameraScreen(this.cameras);

@override
State<StatefulWidget> createState() {
 return _CameraScreenState();
 }
}

class _CameraScreenState extends State<CameraScreen> {
  String imgPath;
  bool _toggleCamera = false;
  CameraController controller;

  @override
  void initState() {
    try {
      SelectedCamera(widget.cameras[0]);
    } catch (e) {
      print(e.toString());
    }
    super.initState();
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget?.cameras?.isEmpty ?? true) {
      return Container(
        child: Text('No Camera Found'),
      );
    }


if (!controller.value.isInitialized) {
  return Container();
}

return AspectRatio(

再次感谢您的帮助!

flutter dart android-camera ios-camera
1个回答
0
投票

我建议在装入摄像机时将摄像机装入CameraWidget并使用FutureBuilder显示默认视图。

class CameraScreen extends StatefulWidget {
  State<StatefulWidget> createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraWidget> {
  Future<List<Camera>> getCameras() async {
    final cameras = await availableCameras();
    return cameras;
  }

  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getCameras(),
      builder: (_, snapshot) {
        if (!snapshot.hasData) {
          return Text('Loading cameras...');
        }

        final cameras = snapshot.data;

        if (cameras.isEmpty) {
          Text('No camera found')
        }

        return AspectRatio(
          ...
        );
      },
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.