翩翩起舞 :- 用相机拍照

我是Flutter的新手,我写了下面的代码,用于在Image.然而,相机预览在我的手机上不显示,圆形指示器一直旋转。我无法查看相机。

import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

class CameraDemo extends StatefulWidget {
  @override
  _CameraDemoState createState() => _CameraDemoState();
}

class _CameraDemoState extends State<CameraDemo> {
  CameraController _control;
  Future<void> _future;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initApp();
  }

  void _initApp() async
  {
    WidgetsFlutterBinding.ensureInitialized();
    final cameras = await availableCameras();
    final firstCam = cameras.first;

    _control = CameraController(
      firstCam,
      ResolutionPreset.high,
    );

    _future = _control.initialize();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _control.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Save Picture")),
      body: FutureBuilder<void>(
        future: _future,
        builder: (context, snapshot) {
        if(snapshot.connectionState==ConnectionState.done)
          return CameraPreview(_control);
        else
          return Center(child: CircularProgressIndicator(),);

        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.camera_alt),
        onPressed: () async {
          try {
            await _future;

            final path = join(
              (await getTemporaryDirectory()).path,
              '${DateTime.now()}.png',
            );

            await _control.takePicture(path);
            Navigator.push(context, MaterialPageRoute(
                builder: (context){
                  return DisplayPicture(imagepath:path);
                },
            ));
          } catch (e) {
            print(e);
          }
        },
      ),
    );
  }


  }

  class DisplayPicture extends StatelessWidget {
  String imagepath;
  DisplayPicture({this.imagepath});

  @override
    Widget build(BuildContext context) {
        return Scaffold(
        appBar: AppBar(title: Text('Display the Picture')),
        // The image is stored as a file on the device. Use the `Image.file`
        // constructor with the given path to display the image.
        body: Image.file(File(imagepath)),
      );
    }
  }

解决方案:

你需要使用 image_picker 库,用于从相机和图库中提取图像,请查看下面的代码,我已经将其用于相机和图库。

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_picker/image_picker.dart';

class HomeScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomeScreen();
  }
}

class _HomeScreen extends State<HomeScreen> {
  File imageFile = null;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue,
          title: Text(
            "HomeScreen",
            textAlign: TextAlign.center,
          ),
        ),
        body: SafeArea(
          top: true,
          bottom: true,
          child: Align(
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                Container(
                    width: MediaQuery.of(context).size.width * 0.35,
                    height: MediaQuery.of(context).size.height * 0.2,
                    margin: EdgeInsets.only(top: 20),
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        shape: BoxShape.circle,
                        image: DecorationImage(
                            image: imageFile == null
                                ? AssetImage('images/ic_business.png')
                                : FileImage(imageFile),
                            fit: BoxFit.cover))),
                SizedBox(
                  height: 10.0,
                ),
                RaisedButton(
                    onPressed: () {
                      _settingModalBottomSheet(context);
                    },
                    child: Text("Take Photo")),
              ],
            ),
          ),
        ));
  }

  //********************** IMAGE PICKER
  Future imageSelector(BuildContext context, String pickerType) async {
    switch (pickerType) {
      case "gallery":

        /// GALLERY IMAGE PICKER
        imageFile = await ImagePicker.pickImage(
            source: ImageSource.gallery, imageQuality: 90);
        break;

      case "camera": // CAMERA CAPTURE CODE
        imageFile = await ImagePicker.pickImage(
            source: ImageSource.camera, imageQuality: 90);
        break;
    }

    if (imageFile != null) {
      print("You selected  image : " + imageFile.path);
      setState(() {
        debugPrint("SELECTED IMAGE PICK   $imageFile");
      });
    } else {
      print("You have not taken image");
    }
  }

  // Image picker
  void _settingModalBottomSheet(context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext bc) {
          return Container(
            child: new Wrap(
              children: <Widget>[
                new ListTile(
                    title: new Text('Gallery'),
                    onTap: () => {
                          imageSelector(context, "gallery"),
                          Navigator.pop(context),
                        }),
                new ListTile(
                  title: new Text('Camera'),
                  onTap: () => {
                    imageSelector(context, "camera"),
                    Navigator.pop(context)
                  },
                ),
              ],
            ),
          );
        });
  }
}

在清单中,你需要为它输入相机,如下所示。

<uses-permission android:name="android.permission.CAMERA" />

还有一个我使用的是默认图片 ic_business.png你可以使用它你的,并确保进入里面的。pubspec.yaml

而图书馆的链接是 点击这里

并将输出如下 enter image description here

给TA打赏
共{{data.count}}人
人已打赏
未分类

Flutter :- 有没有办法自定义列表构建器中每个Expansion Tile的输出?

2022-9-9 2:12:18

未分类

我如何能有响应的页面,通过使用slick插件的滑动图像使用.your-class和多项目类的手机,平板电脑。

2022-9-9 2:12:20

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索